我目前正在处理第三方dll,并且在调用委托OnReceive
时随机发生以下错误:
检测到CallbackOnCollectedDelegate
我读到GC.Collect()
可以使用静态解决问题,但也不能解决问题,我有几个小时并尝试各种方式CallbackOnCollectedDelegate
得到错误,请帮助......
namespace Interfaz
{
class TMPDlg:
{
public CTMIF m_objTMPInterface;
public uint m_dwLocalIP;
public ushort m_nPort;
public byte m_nSubNet;
public uint m_nRadioID;
public uint m_nIndex;
public uint m_dwMobileID;
public int nLength;
public string mensaje_destino;
public string mensaje_recibido;
public TMPDlg()
{
m_objTMPInterface = null;
}
unsafe public void OnReceive(ushort wOpcode, System.IntPtr pbPayload, uint dwSize, uint dwLocalIP)
{
TMReceive(wOpcode, (byte*)pbPayload, dwSize, dwLocalIP);
}
unsafe public void TMReceive(ushort wOpcode, byte * pbPayload, uint dwSize, uint dwLocalIP)
{
// Some Work....
}
public void Send_PrivateMsg(string textBoxMensaje, string labelID)
{
m_nRadioID = uint.Parse(labelID);
mensaje_destino = textBoxMensaje;
nLength = textBoxMensaje.Length;
m_objTMPInterface.SendPrivateMsg(m_nRadioID, mensaje_destino, nLength, 0);
}
public void conect_master(ushort port, string ip)
{
m_objTMPInterface = new CTMIF();
m_dwLocalIP = (uint)IPAddressToNumber(ip);
ADKCALLBACK myOnReceive = new ADKCALLBACK(OnReceive);
m_objTMPInterface.SetCallBackFn(myOnReceive);
//m_objTMPInterface.SetCallBackFn(OnReceive);
m_objTMPInterface.OpenSocket(m_dwLocalIP, port, m_dwMobileID, 10)<
}
答案 0 :(得分:0)
据推测这部分是问题吗?
ADKCALLBACK myOnReceive = new ADKCALLBACK(OnReceive);
m_objTMPInterface.SetCallBackFn(myOnReceive);
如果你有一个类型为ADKCALLBACK
的实例变量,那么只要你的实例在回调函数执行之前(或同时)没有被垃圾收集,你应该没问题。什么控制你的实例的生命周期?
class TMPDlg
{
// Instance variable to protect from garbage collection
private readonly ADKCALLBACK receiveCallback;
public TMPDlg()
{
receiveCallback = myOnReceive;
}
...
public void ConnectMaster(ushort port, string ip)
{
...
m_objTMPInterface.SetCallBackFn(receiveCallback);
...
}
}
(顺便说一下,你的命名可以得到显着改善,你应该避免使用公共字段。)