As mentioned in the previous section, threads outside the windows form cannot directly access its references. They can be implemented through several methods and attributes such as invoke () using delegation.
The example is very simple. There is no way to do this. There is only one button and one lable on the form. click the button to enable a thread for processing. During the processing process, the lable shows the processing progress.
In this example, the thread class is used to create a thread. The button event is very simple,CodeAs follows:
1 Private Void Button#click ( Object Sender, eventargs E)
2 {
3Thread thread= NewThread (NewThreadstart (threadrun ));
4Thread. Start ();
5}
A new thread is implemented here, And threadstart without parameters is used. Then, the thread's start () method is called to start the thread. Here we mainly look at the thread processing process.
As mentioned above, you need to use the invoke method to implement it. A heavy-load style used in this method is as follows:
It receives a delegate type and an object array type. Define a delegate as follows:
Delegate Void Setlabletextcallback ( String TXT );
As above, this delegate is a method definition with the string parameter. The method to implement this structure is as follows:
1 Public Void Setlabletext ( String Text)
2 {
3 If ( This . Label1.invokerequired)
4 {
5 Setlabletextcallback callback = New Setlabletextcallback (setlabletext );
6 This . Invoke (
7 Callback, New Object [] {Text} );
8 }
9 Else
10 {
11This. Label1.text=Text;
12}
13 }
As shown above, the method first judges the property invokerequired, creates a delegate, and calls the invoke method.
The above is just a simple example, and other operations (interrupt, cancel, recover) on the thread are not implemented.
Remember that the thread must be terminated when the page is closed. The thread defaults to the foreground thread, so it will not be closed as the form is closed, when the thread processes the Form Control, null reference and other exceptions may occur.
Over!