开发者

Cross-thread operation not valid in C# [duplicate]

This question already has answers here: Closed 12 years ago.

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 开发者_如何学Pythonupdate 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;
      }     
 }


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


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";
                      });


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜