简体   繁体   中英

Cross Thread after 20 seconds running

I receive data from a serial port and I show all the received data in the format they arrive in a multiline text box. This is my serial monitor "txtOutput". After I have validated the data as complete messages and filtered out few characters (in a separate class), I need to show those data to additional text boxes (textBox7, 2 and 6). For some reason that I am not able to understand, after 10 to 20 seconds of debugging, with messages coming in continuously (200-300 ms), I get a cross thread error, "Cross-thread operation not valid: Control accessed from a thread other than the thread it was created on".

This is my code:

Serial port reading

 private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
        {
            try
            {
                SetText(serialPort1.ReadExisting());
            }
            catch (Exception ex)
            {
                SetText(ex.ToString());
            }
        }

Delegate SetText

delegate void SetTextCallback(string text);

Receive the serial port data and elaborate

  private void SetText(string text)
        {
            if (this.txtOutput.InvokeRequired)
            {
             SetTextCallback d = new SetTextCallback(SetText);
             this.BeginInvoke(d, new object[] { text });
            }
            else
            {
               txtOutput.AppendText(text);
            }
               string a="", b="", c="";
                    string invia = text.ToString();
                    Stripper strp = new Stripper();
                    strp.Distri(invia, out a, out b, out c);
                    textBox7.Text = a; // Current
                    textBox2.Text = b; //Temperature
                    textBox6.Text = c; //RPM
               }
           }

This is one of my first app. What do I need to change to avoid the cross thread error and where is the mistake I made?

You've got some code that changes UI elements outside the part protected by the InvokeRequired. All the text boxes need to be protected too.

Try this:

private void SetText(string text)
{
    if (this.txtOutput.InvokeRequired)
    {
        SetTextCallback d = new SetTextCallback(SetText);
        this.BeginInvoke(d, new object[] { text });
    }
    else
    {
        txtOutput.AppendText(text);
        string a="", b="", c="";
        string invia = text.ToString();
        Stripper strp = new Stripper();
        strp.Distri(invia, out a, out b, out c);
        textBox7.Text = a; // Current
        textBox2.Text = b; //Temperature
        textBox6.Text = c; //RPM
    }
}           

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM