我正在使用BackgroundWorker来获取数据并更新我的UI。这段代码非常自我解释。当我点击连接时,它连接到CANbus,启动后台工作程序,它获取数据并更新UI,当我点击断开连接时,它停止从CANbus获取数据。
它仅适用于第一次,当我第二次尝试连接时,我在RunWorkerAsync调用中获得异常,这是在RunWorkerCompleted回调中,关于BackgroundWorker正忙,并且它不能同时处理多个任务。
这就是我不太明白的,我在每个连接上都创建了BackgroundWorker的新实例,并且不知道为什么它很忙。
寻求建议 - 谢谢。
CANALHandle h;
BackgroundWorker canWorker;
private void bConnect_Click(object sender, RoutedEventArgs e)
{
if (this.h == 0) {
this.h = CANAL.CANALOpen("ED000200; 500", CANAL.FLAG_NONE);
canWorker = new BackgroundWorker();
canWorker.WorkerSupportsCancellation = true;
canWorker.WorkerReportsProgress = true;
canWorker.DoWork += (object s, DoWorkEventArgs ev) => {
if (CANAL.CANALDataAvailable(this.h) > 0) {
CANALMSG msg;
CANALStatus st = CANAL.CANALReceive(this.h, out msg);
ev.Result = msg;
}
};
canWorker.RunWorkerCompleted += (object s, RunWorkerCompletedEventArgs ev) => {
if (ev.Error != null) {
} else if (ev.Result != null) {
CANALMSG msg = (CANALMSG)ev.Result;
if (msg.id > 0) {
textCanId.Text = msg.id.ToString("X");
textCanLength.Text = msg.count.ToString("X");
textCanByte0.Text = (msg.count >= 1) ? msg.data[0].ToString("X2") : "";
textCanByte1.Text = (msg.count >= 2) ? msg.data[1].ToString("X2") : "";
textCanByte2.Text = (msg.count >= 3) ? msg.data[2].ToString("X2") : "";
textCanByte3.Text = (msg.count >= 4) ? msg.data[3].ToString("X2") : "";
textCanByte4.Text = (msg.count >= 5) ? msg.data[4].ToString("X2") : "";
textCanByte5.Text = (msg.count >= 6) ? msg.data[5].ToString("X2") : "";
textCanByte6.Text = (msg.count >= 7) ? msg.data[6].ToString("X2") : "";
textCanByte7.Text = (msg.count >= 8) ? msg.data[7].ToString("X2") : "";
}
}
canWorker.RunWorkerAsync();
};
canWorker.RunWorkerAsync();
}
}
private void bDisconnect_Click(object sender, RoutedEventArgs e)
{
if (this.h > 0) {
canWorker.CancelAsync();
canWorker.Dispose();
CANAL.CANALClose(this.h);
this.h = 0;
}
}