【发布时间】:2016-04-20 22:36:06
【问题描述】:
我有一个与机器的通信接口,并获得了一个提供许多功能的 dll。一切正常,只要我进行通信。如果在 5 分钟内没有什么可以交流的,那么这些功能就不再起作用了。我想这是因为它都被垃圾收集器清理了。经过一些研究,我可能应该用GCHandle.Alloc(object, GCHandleType.Pinned); 固定它
这里是一些代码:
对象
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
public class DNCC_PARAM
{
public int nMacNo;
public int nOwnPort;
public int nIpAddr;
public int nNCPort;
[MarshalAsAttribute(UnmanagedType.FunctionPtr)]
public Delegate CallBackFunction;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 20)]
public short[] arrTimeout = new short[20];
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 20)]
public short[] arrRetry = new short[20];
}
一些 dll 导入
[DllImport(@"path to dll", CharSet = CharSet.Ansi)]
public static extern int Initialize([In()] DNCC_PARAM dncPara);
[DllImport(@"path to dll", CharSet = CharSet.Ansi)]
private static extern int dncc_Connect(int hdl);
[DllImport(@"path to dll", CharSet = CharSet.Ansi)]
private static extern int dncc_Disconnect(int hdl);
对象的实例
DNCC_PARAM param = new DNCC_PARAM();
初始化通信
// fill the object with some data
param.nMacNo = 1;
param.nOwnPort = 7005;
param.nIpAddr = (int)IPAddress.Parse("192.168.0.10").Address;
param.nNCPort = 7005;
param.CallBackFunction = new TypeOfCallBackFunction(AppCallBack);
// init the communication
nDNCC_HANDLE = Initialize(param);
回调函数
private void AppCallBack(int iHandle, int iEvent, IntPtr arg)
{
// doing some stuff here
}
所以当我尝试像GCHandle.Alloc(param, GCHandleType.Pinned); 那样固定对象时,我收到一条消息,指出该对象不包含原始数据。如何防止对象被 GC 清除?
我目前的“解决方案”是一个计时器,它每分钟左右都会进行一些通信。我工作,但我猜是相当丑陋。
【问题讨论】:
标签: c# object garbage-collection unmanaged