错误内容:
在海康威视一体机车牌抓拍的时候
发生了 CallbackOnCollectedDelegate
Message: 托管调试助手“CallbackOnCollectedDelegate”在“E:\科锋工作\物料监控系统\工地端软件\海康威视版\ConstructionSite\bin\Debug\ConstructionSite.vshost.exe”中检测到问题。
其他信息: 对“ConstructionSiteBLL!ConstructionSiteDAL.CHCNetSDK+MSGCallBack::Invoke”类型的已垃圾回收委托进行了回调。这可能会导致应用程序崩溃、损坏和数据丢失。向非托管代码传递委托时,托管应用程序必须让这些委托保持活动状态,直到确信不会再次调用它们。
错误原因在设置回调函数时,实在布防函数中新建的委托,所以在布防函数完成以后,回调委托就可能被GC给回收了,导致以上错误,或者报空指针异常。
错误代码
public static bool SetCameraAlarm(LicensePlateCamera lpc)
{
CHCNetSDK.MSGCallBack m_falarmData = new CHCNetSDK.MSGCallBack(MsgCallback);
CHCNetSDK.NET_DVR_SetDVRMessageCallBack_V30(m_falarmData, IntPtr.Zero);
GC.KeepAlive(m_falarmData);
CHCNetSDK.NET_DVR_SETUPALARM_PARAM struAlarmParam = new CHCNetSDK.NET_DVR_SETUPALARM_PARAM();
struAlarmParam.dwSize = (uint)Marshal.SizeOf(struAlarmParam);
struAlarmParam.byLevel = 1; //0- 一级布防,1- 二级布防
struAlarmParam.byAlarmInfoType = 0;//智能交通设备有效,新报警信息类型
{
CHCNetSDK.MSGCallBack m_falarmData = new CHCNetSDK.MSGCallBack(MsgCallback);
CHCNetSDK.NET_DVR_SetDVRMessageCallBack_V30(m_falarmData, IntPtr.Zero);
GC.KeepAlive(m_falarmData);
CHCNetSDK.NET_DVR_SETUPALARM_PARAM struAlarmParam = new CHCNetSDK.NET_DVR_SETUPALARM_PARAM();
struAlarmParam.dwSize = (uint)Marshal.SizeOf(struAlarmParam);
struAlarmParam.byLevel = 1; //0- 一级布防,1- 二级布防
struAlarmParam.byAlarmInfoType = 0;//智能交通设备有效,新报警信息类型
lpc.AlarmHandle = CHCNetSDK.NET_DVR_SetupAlarmChan_V41(lpc.UserId, ref struAlarmParam);
if (lpc.AlarmHandle < 0)
{
return false;
if (lpc.AlarmHandle < 0)
{
return false;
}
else
{
return true;
}
}
else
{
return true;
}
}
正确代码:
public static CHCNetSDK.MSGCallBack m_falarmData = new CHCNetSDK.MSGCallBack(MsgCallback);
public static bool SetCameraAlarm(LicensePlateCamera lpc)
{
{
CHCNetSDK.NET_DVR_SetDVRMessageCallBack_V30(m_falarmData, IntPtr.Zero);
GC.KeepAlive(m_falarmData);
CHCNetSDK.NET_DVR_SETUPALARM_PARAM struAlarmParam = new CHCNetSDK.NET_DVR_SETUPALARM_PARAM();
struAlarmParam.dwSize = (uint)Marshal.SizeOf(struAlarmParam);
struAlarmParam.byLevel = 1; //0- 一级布防,1- 二级布防
struAlarmParam.byAlarmInfoType = 0;//智能交通设备有效,新报警信息类型
GC.KeepAlive(m_falarmData);
CHCNetSDK.NET_DVR_SETUPALARM_PARAM struAlarmParam = new CHCNetSDK.NET_DVR_SETUPALARM_PARAM();
struAlarmParam.dwSize = (uint)Marshal.SizeOf(struAlarmParam);
struAlarmParam.byLevel = 1; //0- 一级布防,1- 二级布防
struAlarmParam.byAlarmInfoType = 0;//智能交通设备有效,新报警信息类型
lpc.AlarmHandle = CHCNetSDK.NET_DVR_SetupAlarmChan_V41(lpc.UserId, ref struAlarmParam);
if (lpc.AlarmHandle < 0)
{
return false;
if (lpc.AlarmHandle < 0)
{
return false;
}
else
{
return true;
}
}
else
{
return true;
}
}
总结:
不仅仅是变量,委托也要注意生命周期,防止被GC清除,导致调用回掉失败。