Keep getting cross thread error and cannot figure out a potential fix RRS feed

All replies

  • Please read SerialPort Class.

    The communication is already handled on a separate thread by SerialPort. No need for an extra background worker.

    Just use the DataRecieved event of SerialPort. Here read the data into a buffer and evaluate this buffer. But it depends strongly on the kind of protocol used by your device. E.g. something like

    private SerialPort serialPort;
    private void serialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
    	this.buffer += this.serialPort.ReadExisting();
    	string datagram = this.DequeueDatagram();
    	while (datagram != null) {
    		datagram = this.DequeueDatagram();
    private string DequeueDatagram()
    	string result = null;
    	bool containsDatagram = someLogicTest;
    	if (containsDatagram)
    		result = retrieveDatagramFromBuffer;
    		this.buffer = removeDatagramFromBuffer;
    	return result;
    private void HandleDatagram(string datagram)
    	//Do something

    Saturday, December 22, 2018 9:55 PM
  • The serial port works fine the problem is that i am using a richtextbox to input some text, and then send that text line by line to a textbox which is sent trough the serial. If i move the code from the backgroundworker_DoWork event to the Send event, the code works like intended but the Form freezes. Thats why i tryed to use the backgroundworker to release my form, but i get the cross thread error.

    Saturday, December 22, 2018 10:28 PM
  • Read the links.

    SerialPort works on a separate thread. This means that you need to synchronize calls from there to the UI thread. You need to call InvokeRequired and Invoke to do that.

    • Marked as answer by Notoriousg13 Sunday, December 23, 2018 12:21 AM
    • Unmarked as answer by Notoriousg13 Sunday, December 23, 2018 12:21 AM
    Saturday, December 22, 2018 11:09 PM
  • I have tried to invoke the line 

    string[] lines = Regex.Split(richTextBox1.Text, "\n");

    But it did not work, i guess i was doing something wrong... How do i invoke this line ?

    Sunday, December 23, 2018 12:23 AM
  • I can't tell, cause I don't see what your code should do. Maybe you should clean it up, post it again and please explain what each method is supposed to do.
    Sunday, December 23, 2018 1:26 AM
  • Content Removed
    Sunday, December 23, 2018 5:12 AM