In C # WinForm development, this is a more common exception: An invalid thread operation, which is accessed from a thread that is not creating the control "XXX". This anomaly comes from. A limitation of NET2: A worker thread cannot access a control created by a window thread. There are two main solutions, one is to set checkforillegalcrossthreadcalls = False in the window thread, and the other is cumbersome, invoking the Invoke method using a delegate.
For example, there is a button1 in the window, I want to create a new thread to access the button1. The first way is:
code is as follows |
copy code |
This.button1.Enabled = false; New Thread (New ThreadStart (delegate () { br> try { Checkforillegalcrossthreadcalls = false; //Direct setting throws an exception: invalid thread operation, access to the thread that never creates the control this.button1.Enabled = true; }catch (Exception ex) { MessageBox.Show (ex. ToString ()); } }). |
Start (); Use a delegate
The code is as follows |
Copy Code |
<summary> Declaring a delegate </summary> <param name= "button" ></param> <param name= "state" ></param> Private delegate void _setbuttonstate (Button button,bool state); <summary> Set the status of a button </summary> <param name= "button" > button </param> <param name= "state" ></param> private void Setbuttonstate (Button button,bool State) { The request for the control comes from a thread that is not in the process of creating the control if (button. invokerequired) { _setbuttonstate _set = new _setbuttonstate (delegate (Button _button, BOOL _state) { _button. Enabled = _state; }); This. Invoke (_set, button, state); } Else { button. Enabled = State; } } |
And then access the control button1 from the new thread
The code is as follows |
Copy Code |
This.button1.Enab LED = false; New Thread (New ThreadStart (delegate () { try { //Direct setting throws an exception: An invalid thread operation, a thread that never creates a control, accesses it / Checkforillegalcrossthreadcalls = false; //this.button1.Enabled = true; //Delegate Way Setbuttonstate (button1,true); }catch (Exception ex) { MessageBox.Show (ex. ToString ()); } }). Start (); |