也许我需要将标题更改为“非托管代码调用会导致大量内存泄漏!”
泄漏量约为30M /小时
我想也许我需要在这里完成我的代码,因为内存泄漏可能不是来自静态字符串,而我的真实代码从外部设备派生此字符串(请参阅附加的新代码)。所以我也处理非托管代码。泄漏是否可能来自非托管代码?但我释放了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是一个类,最后它将调用下面定义的COM组件
[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);
}