Cross-thread delegation and exclusion

Whenever I update the user interface on a Windows form with a delegate, it gives me a cross-thread exception, why is this happening? is there a new thread for every delegate call?

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; }));
     }
 }
+3
source share
4 answers

Port_DataReceived is obviously an async event handler that is created by the port monitoring component thread.

there is a new thread for each delegate call?

No, probably not. The port monitoring component starts polling in the background thread, and an event is generated from this thread each time.

, , , 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);
    }
}

, , .

+2

DataReceived threadpool. , Control.BeginInvoke(). InvokeRequired, .

, :

  • Control.BeginInvoke , . , . , , . SerialPort.ReadLine() , , (SerialPort.NewLine).
  • . , , . ObjectDisposed. FormClosing . , .
  • Control.Invoke BeginInvoke. , SerialPort.Close().

. , DataReceived, .

+5

Cross Thread , . , . , , .

0

A cross-flow exception occurs when some user interface threads modify user interface elements. To fix this, use the Invoke method for the control itself. As an extra, you can check InvokeRequired on the control before calling the Invoke method. See msdn

0
source

Source: https://habr.com/ru/post/1741890/


All Articles