1

我正在使用 USB 设备。此设备接收消息,我不知道何时或多久。驱动程序附带的 API 指定了一个 setreceiveCallBack 函数,该函数在设备接收到消息时提供回调。但是在随机时间或间隔,我会收到有关垃圾收集委托异常的回调。我已经为我的问题寻找解决方案,但似乎没有一个解决方案适用于我的情况。以下是我的代码的最大部分:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
using System.Windows.Forms;

namespace CallBacktesting
{
    public unsafe delegate void callBack(Form1.CANMsg *pmsg);

    public partial class Form1 : Form
    {
        uint handle;
        static WriteLog log = new WriteLog();
        Boolean getCan = false;
        static int frameCount = 0;
        static CANMsg newmsg = new CANMsg();
        callBack _setCallBack;
        List<string> write = new List<string>();

        public Form1()
        {
            InitializeComponent();
        }


        private void buttonOpen_Click(object sender, EventArgs e)
        {
                // Open connection
        }

        private void buttonClose_Click(object sender, EventArgs e)
        {
               // Close connection
        }

        private void buttonCallBack_Click(object sender, EventArgs e)
        {
            if (!getCan)
            {
                int rv;
                unsafe
                {
                    callBack _setCallBack = new callBack(call);
                    rv = canusb_setReceiveCallBack(handle, _setCallBack);
                }
                label1.Text = rv.ToString();
            }
            else
            {
                _setCallBack = null;
                int rv = canusb_setReceiveCallBack(handle, _setCallBack);
                GC.KeepAlive(_setCallBack);
                label1.Text = rv.ToString();
            }
        }

        public unsafe void call(CANMsg *pmsg)
        {
            newmsg = *pmsg;
            update();
        }

        private void buttonExit_Click(object sender, EventArgs e)
        {
            GC.KeepAlive(_setCallBack);
            Application.Exit();
        }

        [DllImport("canusbdrv.dll", EntryPoint = "canusb_setReceiveCallBack")]
        public static extern int canusb_setReceiveCallBack(uint handle, callBack callBack);

        unsafe private void timer_Tick(object sender, EventArgs e)
        {
              // update the form with received messages
        }

        public void update()
        {
            CANMsg msgrec = newmsg;
            // Build str from messages with all data
            write.Add(str);
            log.logWrite(str);
            frameCount++;
        }
    }

    public class WriteLog
    {

        private void OpenFile()
        {     }

        public void logWrite(string log)
        {     }

        public void logAdd(string log)
        {     }

        private void logClose()
        {     }
    }
}
4

2 回答 2

2

这是正确的/错字吗?:

callBack setCallBack = new callBack(call);
rv = canusb_setReceiveCallBack(handle, call);

您似乎创建了一个回调实例,但随后将其他内容传递给canusb_setReceiveCallBack-您是要传递setCallBack吗?

此外,在这一行中,您将 setCallBack 声明为局部变量,因此即使您传递setCallBack而不是call,您仍然传递了一个本地范围的变量,该变量可能会被垃圾收集(我注意到您这样做是GC.KeepAlive(setCallBack); 为了明确防止这种情况发生)

于 2009-11-30T13:30:16.470 回答
2

在您的代码中,当您这样做时



                callBack setCallBack = new callBack(call);
                rv = canusb_setReceiveCallBack(handle, call);

调用“canusb_setReceiveCallBack”后,该委托将可用于垃圾收集,因为您的代码中没有引用该委托。

您可以避免将其存储在私有字段中。

前任:


Class Form1
{

callBack _setCallBack;

private void buttonCallBack_Click(object sender, EventArgs e)
{


                _setCallBack = new callBack(call);
                rv = canusb_setReceiveCallBack(handle, _setCallBack);

}

}

但这可能会有一些问题,因为每次按钮点击都会创建一个新的回调。如果需要引用先前的回调,这可能会出现问题。

我认为您应该做的是重构代码以使用SafeHandle来存储 canusb_Open 返回的句柄。

我会这样设计课程。


class CanUsbSafeHandle : SafeHandle
{
    private EventHandler _receiveCallBack;
    private readonly object _receiveCallBackLock = new object();

    public event EventHandler ReceiveCallBack
    {
        add
        {
            lock (_receiveCallBackLock)
            {
                bool hasListeners = (_receiveCallBack != null);
                _receiveCallBack += value;
                //call canusb_setReceiveCallBack only when 1 or more listeners were added
                //and there were previously no listeners
                if (!hasListeners && (_receiveCallBack != null))
                {
                    canusb_setReceiveCallBack(this, setCallBack);
                }
            }
        }
        remove
        {
            lock (_receiveCallBackLock)
            {
                bool hasListeners = (_receiveCallBack != null);
                _receiveCallBack -= value;
                //call canusb_setReceiveCallBack only when there are no more listeners.
                if(hasListeners && (_receiveCallBack == null))
                {
                    canusb_setReceiveCallBack(this, null);
                }
            }
        }
    }

    public CanUsbSafeHandle()
        : base(IntPtr.Zero, true)
    {
    }

    public override bool IsInvalid
    {
        get { return handle == IntPtr.Zero; }
    }

    protected override bool ReleaseHandle()
    {
        return canusb_Close(handle);
    }

    protected override void Dispose(bool disposing)
    {
        if (disposing)
        {
            lock (_receiveCallBackLock)
            {
                _receiveCallBack = null;
            }
        }
        base.Dispose(disposing);
    }
}

这样,SafeHandle 将管理“接收回调”委托的生命周期将由 SafeHandle 管理。

于 2009-11-30T13:48:19.187 回答