Skip to content

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

Gary B

Asked Nov 29, 2010, 10:08 PM EST1 answer
Share
LinkedInX
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

 

C#
 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."
   

    }

1 Answer

Know the answer? Post it. Somebody with the same question will find it here.

  • 1 short reply
    • Suthish Nair
      0
      refer link, might helps
      0