每当我使用委托更新 Windows窗体中的UI时,它就会给我跨线程异常 为什么会这样? 是否为每个代表调用启动了新线程? void Port_DataReceived(object sender, SerialDataReceivedEventArgs e){ //this call del
为什么会这样?
是否为每个代表调用启动了新线程?
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; })); } }Port_DataReceived显然是由端口监视组件上的线程引发的异步事件处理程序.
is there new thread started for each
delegate call ?
不,可能不是.您的端口监视组件正在后台线程上运行轮询,并且每次都从该线程引发事件.
关键是它是在UI以外的线程上调用的,因此您需要使用Control.Invoke以及与之关联的模式.
考虑一下,(并阅读post可能会为你阐明的事情)
void Port_DataReceived(object sender, SerialDataReceivedEventArgs e) { //this call delegate to display data UpdateTheUI(statusMsg); } private void UpdateTheUI(string statusMsg) { if (lblMsgResp.InvokeRequired) { lblMsgResp.BeginInvoke(new MethodInvoker(UpdateTheUI,statusMsg)); } else { clsConnect(statusMsg); } }
尽管如此,如果我没有指出间接是令人不安的话,那将是我的疏忽.