我的C#应用​​程序的内存使用量增加

时间:2016-12-09 06:05:22

标签: c# memory marshalling

我有一个C#应用程序来控制和监视PMAC控制器。这个应用程序应该至少可以运行几天,但我发现它的内存使用量会一直增加。最初内存使用量约为230M,每小时增加25M。

我发现除非我调用ReadDataFromDPRam()方法,否则内存不会增加。

我称此方法为10毫秒间隔。

[StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct PmacServoRead
{
   [MarshalAs(UnmanagedType.ByValArray, SizeConst = (int)MotorNo.All)]
   public float[] CurPosition; // M4000, 
   [MarshalAs(UnmanagedType.ByValArray, SizeConst = (int)MotorNo.All)]
   public float[] CurVelocity;
   public int AmpEnable;
   public int PosLimit;
   public int NegLimit;
   public int HomeComp;
   public int DesiredVelocityZero;
   ...
}

[DllImport("Pcomm32.dll")]
public static extern IntPtr PmacDPRGetMem(UInt32 dwDevice, UInt32 offset, UInt32 count, IntPtr val);

public IntPtr GetDpramMemory(UInt32 devNo, UInt32 offset, UInt32 count, IntPtr val)
{
   return PmacDPRGetMem(devNo, offset, count, val);
}

private PmacServoRead m_PmacServoRead = new PmacServoRead();
private PmacInput m_PmacInput = new PmacInput();
int m_ReadSize = Marshal.SizeOf(typeof(PmacServoRead));
int m_ReadSizeDi = Marshal.SizeOf(typeof(PmacInput));

private int ReadDataFromDPRam()
{
   if (IsOpen == true)
   {
      IntPtr ptr1 = Marshal.AllocHGlobal(m_ReadSize);
      GetDpramMemory(DeviceNo, CcpPmacComm.DpramReadOffset, (uint)m_ReadSize, ptr1);
      m_PmacServoRead =(PmacServoRead)Marshal.PtrToStructure(ptr1, typeof(PmacServoRead));
      Marshal.DestroyStructure(ptr1, typeof(PmacServoRead));
      Marshal.FreeHGlobal(ptr1);

      ptr1 = Marshal.AllocHGlobal(m_ReadSizeDi);
      GetDpramMemory(DeviceNo, CcpPmacComm.DpramInputReadOffset, (uint)m_ReadSizeDi, ptr1);
      m_PmacInput = (PmacInput)Marshal.PtrToStructure(ptr1, typeof(PmacInput));
      Marshal.DestroyStructure(ptr1, typeof(PmacInput));
      Marshal.FreeHGlobal(ptr1);
   }
   return -1;
}

请帮帮我。

0 个答案:

没有答案