我正在使用USB設備。此設備接收消息,我不知道何時或多久。驅動程序附帶的API指定了一個setreceiveCallBack函數,該函數在設備收到消息時提供回調。 但隨機的時間或間隔,我收到garbagecollected委託exeption回調。我已經爲我的問題尋找解決方案,但沒有一個解決方案似乎適用於我的情況。 以下是我的代碼的最重要的部分:回收垃圾收集代表
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()
{ }
}
}
我刪除了一些代碼的可讀性和糾正錯誤(用_setCallBack代替setCallBack) – 2009-12-01 09:17:34