In the case of multiple threads, other threads cannot directly call controls on the main thread. They can only call controls on the main thread through proxies.
1. Define Delegation
// Delegate statement for executing the task (solving the long task death false)
Delegate void RunTaskDelegate (int seconds );
// Display the delegate Declaration of the progress bar (cross-thread Call Control)
Delegate void ShowProgressDelegate (int totalStep, int currentStep );
2. Definition Method
Private void ShowProgress (int totalStep, int currentStep)
{
ProgressBar1.Maximum = totalStep;
ProgressBar1.Value = currentStep;
}
3. Define a thread
Private void RunTask (int seconds)
{
ShowProgressDelegate showProgress = new ShowProgressDelegate (ShowProgress );
For (int I = 0; I <seconds * 4; I ++)
{
Thread. Sleep (250 );
// Call the delegate that displays the progress bar in the basic window
This. Invoke (showProgress, new object [] {seconds * 4, I + 1 });
}
}
4. Execute
RunTaskDelegate runTask = new RunTaskDelegate (RunTask );
// Call the task delegate Asynchronously
RunTask. BeginInvoke (20, null, null );