This method can be used to call background programs, create threads, and screen masking.
BackgroundWorker has three main events: RunWorkerCompleted, ProgressChanged, and DoWork.
[Csharp]
This. backgroundWorker1.RunWorkerCompleted + = new RunWorkerCompletedEventHandler (backgroundworkerappsrunworkercompleted );
This. backgroundWorker1.ProgressChanged + = new ProgressChangedEventHandler (backgroundWorker1_ProgressChanged );
This. backgroundWorker1.DoWork + = new DoWorkEventHandler (backgroundworker+dowork );
When you click a button to implement the read entry method, you need to call the RunWorkerAsync method of the BackgroundWorker object. This method will trigger the DoWork event.
You can obtain the BackgroundWorker object in two ways,
[Csharp]
Private void backgroundworker=dowork (object sender, DoWorkEventArgs e)
{
BackgroundWorker worker = (BackgroundWorker) sender;
Lt;
}
Alternatively, you can directly obtain the BackgroundWorker in the class. In the DoWork method, the details of read record processing are mainly used. The percentage is transferred through the ReportProgress of the BackgroundWorker object,
The Maximum value of 100 in a for loop can be expressed as the denominator of the percentage, which is consistent with the Maximum attribute of progressBar. Note that Thread. Sleep (100) must be added. Otherwise, the Thread is always executed and other controls on the main panel cannot be used, and the current Thread cannot be canceled. In each loop, check whether the CancellationPending is true to indicate whether the current thread is interrupted by the user.
[Csharp]
For (int I = 0; I <100; I ++)
{
If (bk. CancellationPending) // determine whether the user needs to cancel the background and exit as soon as possible.
{
Bk. ReportProgress (I, String. Format ("the current value is {0}, the operation was interrupted by the user application", I ));
Return false;
}
Thread. Sleep (100 );
// Report the processing progress to the main thread through this function during processing. It is best to convert the progress to a percentage, which must correspond to the maximum value of the progress bar outside. Here, I did not translate, but adjusted the maximum progress bar value of the interface thread to be consistent with the total number here.
Bk. ReportProgress (I, String. Format ("{0} %", I ));
}
You can call the CancelAsync method to terminate the background thread. The RunWorkerCompleted method is set for termination in any way.
The last thing to talk about is the progressChanged event, which is triggered by ReportProgress. It is generally used to respond to messages when the background thread value changes to process the display of the interface.
For example:
[Csharp]
Private void backgroundWorker1_ProgressChanged (object sender, ProgressChangedEventArgs e)
{
This. progressBar1.Value = e. ProgressPercentage;
This. label1.Text = e. UserState. ToString ();
This. label1.Update ();
}
Author: haqer0825