In the form program, we often open another thread for time-consuming operations, but we need to know the running status of the new thread and operate the UI thread to display the status of the new thread. For example:
C # code
Namespace CrossCall
{
Public partial class Form1: Form
{
Thread thread = null;
Public Form1 ()
{
InitializeComponent ();
// Checkforillegalcrossthreadcils = false;
Thread = new Thread (fun );
Thread. Start (); // enable a new thread
}
Private void fun ()
{
Int I = 10;
While (I --> 0)
{
Label1.Text = I. ToString (); // update the UI control in the new thread
Thread. Sleep (1000 );
}
}
// If the thread is still running after the program is closed, the thread is closed.
Private void form=formclosed (object sender, FormClosedEventArgs e)
{
If (thread! = Null)
{
Thread. Abort ();
}
}
}
}
In this case, the program runs incorrectly:
I generally use the following two methods to solve this problem:
1. If the cross-thread call does not cause errors, you can set the Form Control to not check cross-thread call errors, so that no error is reported.
In the Form1 constructor:
C # code
Checkforillegalcrossthreadcils = false;
2. However, to prevent errors caused by simultaneous update of controls by multiple threads, you can also use the proxy method:
The Control. BeginInvoke method (Delegate) asynchronously executes the specified Delegate on the thread where the basic handle of the Control is created.
This is an example of the help document:
C # code
Public delegate void InvokeDelegate ();
Private void Invoke_Click (object sender, EventArgs e)
{
MyTextBox. BeginInvoke (new InvokeDelegate (InvokeMethod ));
}
Public void InvokeMethod ()
{
MyTextBox. Text = "Executed the given delegate ";
}
If we don't write the delegate ourselves, we can use MethodInvoker to delegate:
MethodInvoker provides a simple delegate to call methods that contain the void parameter list. You can use this delegate when calling the control's Invoke method or when you need a simple delegate and do not want to define it yourself.
Therefore, the code can be rewritten:
C # code
Namespace CrossCall
{
Public partial class Form1: Form
{
Thread thread = null;
Public Form1 ()
{
InitializeComponent ();
// Checkforillegalcrossthreadcils = false;
Thread = new Thread (fun );
Thread. Start (); // enable a new thread
}
Private void fun ()
{
Int I = 10;
While (I --> 0)
{
// Label1.Text = I. ToString (); // update the UI control in the new thread
BeginInvoke (new MethodInvoker (delegate ()
{
Label1.Text = I. ToString (); // update the UI control in the new thread
}));
Thread. Sleep (1000 );
}
}
// If the thread is still running after the program is closed, the thread is closed.
Private void form=formclosed (object sender, FormClosedEventArgs e)
{
If (thread! = Null)
{
Thread. Abort ();
}
}
}
}
The program runs normally.