. Net does not allow direct access to the control created by another thread in one thread. It will cause an exception: the Inter-thread operation is invalid and is never accessed by the thread that created the control XXX.
Controls in Windows Forms are bound to specific threads and do not have thread security.
If you call the control method from another thread, you must use one invoke method of the control to mail the call to the appropriate thread.
This article uses a thread to change the text attribute of the label (lb_name) of another thread as an example to implement access to controls between different threads.
1:Declare a delegate and the method signature is a string
public delegate void SetText(string text);
2:Define a method to change the text of lbale, which can be called by different threads. This method can include parameters so that you do not need to use anonymous methods. This method is used to delegate methods.
/// <Summary> /// use the invoke method to access the control and determine whether the control is created by the current thread. /// </Summary> private void setlbtext () {// if true is returned, the thread used to access the control is not the thread used to create the control. If (lb_name.invokerequired) {// an example of a delegate, anonymous method, settext ST = new settext (delegate (string text) {// change the label's textlb_name.text = text;}); // give the call permission to the control creation thread, with the parameter lb_name.invoke (St, "I am another thread --- invoke method");} else {lb_name.text = "this control is created by me --- invoke method ";}}
3:Open a new thread and execute the following methods:
Thread t = new Thread(new ThreadStart(SetLbText));t.Start();
4:Direct access will fail:
// Open a new thread and use the threadstart delegate. The anonymous method thread t = new thread (New threadstart (delegate () {// call try {lb_name.text = "I am another thread";} catch (exception ex) {// different threads cannot access MessageBox. show (ex. message) ;}}); // start thread t. start ();
5: