0

Possible Duplicate:
Cross-thread operation not valid: Control accessed from a thread other than the thread it was created on.

Greeting, I'm trying to update button status from a thread and I'm getting this error:

"Cross-thread operation not valid: Control 'btn1' accessed from a thread other than the thread it was created on."

please advice how to fix this problem.

here is my code:

 if (strMyPlayer == "Player One")
 {
      if (srReceiver.ReadLine() == "Player One says: btn1")
      {
           btn1.Text = "O";
           btn1.Enabled = false; 
      }
 }
 else
 {
      if (srReceiver.ReadLine() == "btn1")
      {
           btn1.Text = "X";
           btn1.Enabled = false;
      }     
 }
Community
  • 1
  • 1
Eyla
  • 5,751
  • 20
  • 71
  • 116
  • 2
    there are at least **20** same questions, also first result in google query will give you solution. I really would like to hear why didn't you do any attempts to find solution. – Andrey Aug 09 '10 at 10:23

3 Answers3

2

Use Control.InvokeRequired and one of Control.Invoke / Control.BeginInvoke methods.

desco
  • 16,642
  • 1
  • 45
  • 56
1

You cannot update a UI element from a background thread. I'm guessing srReceiver runs on a background thread.

You can update it using a delegate:

btn1.Invoke(delegate {
                             btn1.Enabled = "OK";
                             btn1.Text = "X";
                      });
Per-Frode Pedersen
  • 1,027
  • 1
  • 6
  • 15
0

You should maybe use the invoke-function to run the function on the controls thread.

http://msdn.microsoft.com/en-us/library/aa288468(VS.71).aspx

Marcus Johansson
  • 2,626
  • 2
  • 24
  • 44