0co*_*ool 3 c# multithreading delegates
每当我使用委托更新Windows窗体中的UI时,它会给我跨线程异常,为什么会发生这种情况?是否为每个代表调用启动了新线程?
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; }));
}
}
Run Code Online (Sandbox Code Playgroud)
DataReceived事件始终在线程池线程上引发.您无法更新任何UI控件,您必须使用Control.BeginInvoke().没有必要测试InvokeRequired,它总是如此.
这里要记住几件事:
有很多方法可以解决问题.考虑使用您自己的线程,而不是使用DataReceived来避免它们.