1
Reply

Beginner = How to return a variable to Main, from a different thread?

Ask a question
Gary B

Gary B

13y
1.8k
1
Hi,

I have data coming from the serial port (this works ok)

The data is in a string called "RxString"

I then try and print out the string to a textBox1 in the Main thread, but it fails giving me an error (see code for explanation of the error).

It is essential that the string is available in the main thread as I access it with extra data from the Main thread.

 

Can you please help me to find a easy solution


Regards Gary

 

 private void serialPort1_DataReceived(object sender,
System.IO.Ports.SerialDataReceivedEventArgs e)
{
this.Invoke((MethodInvoker)delegate
{
RxString = serialPort1.ReadExisting();
});

Update_textBox1(); // **** FAILS HERE ****
// (Update_textBox1 IS in my Main thread and uses
RxString)

// System.InvalidOperationException was unhandled
// Message="Cross-thread operation not valid: Control
// 'textBox1' accessed from a thread other than the
// thread it was created on."


}


Answers (1)