In. if you need to change the UI control attributes in a non-UI thread, the CLR will throw an exception and prompt that the control (cross-thread operation not valid) on the interface cannot be updated in a non-UI thread ). Generally, there are two solutions. The first is to set the static property checkforillegalcrossthreadcils of control to false, as follows:
View Source
Print?
03 |
Initializecomponent (); |
04 |
Control. checkforillegalcrossthreadcils = False ; |
07 |
Private Void Button#click ( Object Sender, eventargs E) |
09 |
Thread thread = New Thread () => |
11 |
For ( Int I = 0; I <100000; I ++) |
13 |
Label1.text = I. tostring (); |
Another method is to use delegation to determine whether the update operation of the current control is in another thread Based on the invokerequired property of the control. If yes, use the delegate to call the method and update the control. However, this method has the disadvantage of creating separate delegates and methods for the attribute setting method of each control. These delegates and methods are only used for cross-thread operations. For example, when you need to modify the text of a label in another thread, you need to create a setlabeltext method. Suppose you still need to update the text of the textbox, you need to create another settextboxtext method.
Through the following delegation and method definition, we implement "one definition, multiple use ". See:
View Source
Print?
01 |
Private Delegate Void Parameterizedcontrolupdate ( Params Object [] ARGs ); |
03 |
Private Delegate Void Controlupdatedelegate (component C, |
04 |
Parameterizedcontrolupdate callback, |
05 |
Params Object [] ARGs ); |
07 |
Private Void Delegatedcontrolupdate (component C, |
08 |
Parameterizedcontrolupdate callback, |
11 |
Control Target = (C Is Control )? (C As Control ): This ; |
12 |
If (Target. invokerequired) |
14 |
Controlupdatedelegate d = delegatedcontrolupdate; |
15 |
Target. Invoke (D, New Object [] {C, callback, argS }); |
The preceding example can be changed:
View Source
Print?
01 |
Private Void Button#click ( Object Sender, eventargs E) |
03 |
Thread thread = New Thread () => |
05 |
For ( Int I = 0; I <100000; I ++) |
07 |
Delegatedcontrolupdate (label1, argS => |
09 |
Label1.text = ( String ) ARGs [0]; |