0

我目前正在研究第三方 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)<

        }
4

1 回答 1

0

想必这部分有问题?

ADKCALLBACK myOnReceive = new ADKCALLBACK(OnReceive);
m_objTMPInterface.SetCallBackFn(myOnReceive);

如果你有一个type 的实例变量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);
        ...
    }
}

(顺便说一句,您的命名可能会得到显着改进,并且您应该避免使用公共字段。)

于 2012-08-23T16:50:17.883 回答