저는 USB 장치로 작업하고 있습니다. 이 장치는 메시지를 수신하고 언제 또는 얼마나 자주 보내는 지 알 수 없습니다. 드라이버와 함께 제공되는 API는 장치가 메시지를받을 때 콜백을 제공하는 setreceiveCallBack 함수를 지정합니다. 하지만 임의의 시간이나 간격으로 garbagecollected delegate exeption에서 콜백을 수신합니다. 내 문제에 대한 해결책을 찾았지만 해결책 중 어느 것도 내 경우에는 효과가없는 것 같습니다. 다음 내 코드의 가장 큰 부분이다 :콜백에서 garbagecollected 대리인
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 사용). –