gpt4 book ai didi

c# - 委托(delegate)和跨线程异常

转载 作者:行者123 更新时间:2023-11-30 14:19:26 25 4
gpt4 key购买 nike

每当我使用委托(delegate)更新 Windows 窗体中的 UI 时,它都会给我跨线程异常为什么会这样?是否为每个委托(delegate)调用启动了新线程?

void Port_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
//this call delegate to display data
clsConnect(statusMsg);
}




protected void displayResponse(string resp)
{
//here cross thread exception occur if directly set to lblMsgResp.Text="Test";
if (lblMsgResp.InvokeRequired)
{
lblMsgResp.Invoke(new MethodInvoker(delegate { lblMsgResp.Text = resp; }));
}
}

最佳答案

DataReceived 事件总是在线程池线程上引发。您不能更新任何 UI 控件,您必须使用 Control.BeginInvoke()。没有必要测试 InvokeRequired,它始终为真。

这里要记住几件事:

  • 不要为您收到的每个字符或字节调用 Control.BeginInvoke。这将使 UI 线程崩溃。缓冲从串行端口获得的数据,直到获得完整的响应。使用 SerialPort.ReadLine() 通常效果很好,许多设备发送以换行符 (SerialPort.NewLine) 终止的字符串。
  • 关闭您的程序可能很困难。您必须确保在串行端口停止发送之前保持表单处于事件状态。在窗体关闭后获取事件将生成 ObjectDisposed 异常。使用 FormClosing 事件关闭串行端口并启动一秒计时器。只有在计时器到期时才真正关闭表单。
  • 避免使用 Control.Invoke 而不是 BeginInvoke。当您调用 SerialPort.Close() 时,它可能会使您的程序死锁。

惹麻烦的方法有很多。考虑使用您自己的线程而不是使用 DataReceived 来避免它们。

关于c# - 委托(delegate)和跨线程异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2673012/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com