views:

132

answers:

0

Maybe I need change the title as "Unmanaged Code calling leads to heavy memory leak!"

The leak is around 30M/hour

I think maybe I need complete my code here because the memory leak maybe not from a static string whereas my real code derive this string from external device (see new code attached). so I handle also unmanaged code. Could it be possible the leak comes from unmanaged code? But I freed the resouce by Marshal.FreeCoTaskMem(pos);

   oThread2 = new Thread(new ThreadStart(Cyclic_Call));
   oThread2.Start();

  delegate void SetText_lab_Statubar(string text);
  private void m_SetText_lab_Statubar(string text)
  {
   if (this.lab_Statubar.InvokeRequired)
   {
    SetText_lab_Statubar d = new SetText_lab_Statubar(m_SetText_lab_Statubar);
    this.Invoke(d, new object[] { text });
   }
   else
   {
    this.lab_Statubar.Text = text;
   }
  }

  private void Cyclic_Call()
  {
   do
   {  
     //... ...
     ReadMatrixCode(Station6, 0, str_Code);
     this.m_SetText_lab_Statubar(str_Code[4]); 
     Thread.Sleep(100);
   }
   while (!b_AbortThraed);
  }

  private void ReadMatrixCode(Station st, int ItemNr, string[] str_Code)
  {
   IntPtr pItemStates = IntPtr.Zero;
   IntPtr pErrors = IntPtr.Zero;
   int NumItems = itemServerHandles.Length;

   m_SyncIO.Read(DataSrc, NumItems, itemServerHandles,
     out pItemStates, out pErrors); 
// This calls external dll which has some of "out IntPtr" 

   errors = new int[NumItems];
   Marshal.Copy(pErrors, errors, 0, NumItems);
   IntPtr pos = pItemStates;
   // Now get the read values and check errors

   for (int dwCount = 0; dwCount < NumItems; dwCount++)
   {
    result[dwCount] = (ITEMSTATE)Marshal.PtrToStructure(pos, typeof(ITEMSTATE));
    pos = (IntPtr)(pos.ToInt32() + Marshal.SizeOf(typeof(ITEMSTATE)));
   }

   // Free allocated COM-ressouces
   Marshal.FreeCoTaskMem(pItemStates);
   Marshal.FreeCoTaskMem(pErrors);
   pItemStates = IntPtr.Zero; pErrors = IntPtr.Zero;
  }

m_syncIO is a class and finally it will call COM component which is defined below

[Guid("39C12B52-011E-11D0-9675-1020AFD8ADB3")]
[InterfaceType(1)]
[ComConversionLoss]
public interface ISyncIO
{
    void Read(DATASOURCE dwSource, int dwCount, int[] phServer, out IntPtr ppItemValues, out IntPtr ppErrors);
    void Write(int dwCount, int[] phServer, object[] pItemValues, out IntPtr ppErrors);
}