The backgroundWorker provided by Microsoft is a very good component for asynchronous operations. The following describes how to use this component to asynchronously process large volumes of data and display the processing progress with a progress bar. It also provides the cancellation function. Click the button on the main form to bring up the progress bar mode form, prompting the user for data processing progress. As follows:
Call code:
Private void button#click (object sender, EventArgs e)
{
This. backgroundWorker1.RunWorkerAsync (); // run the component
// Display the progress bar form
ProcessForm form = new ProcessForm (this. backgroundWorker1 );
Form. ShowDialog (this );
Form. Close ();
}
DoWork event: processing a large volume of data RunWorkerCompleted event in this event: whether the program is completed normally or you click the cancel button, this event will be triggered private void backgroundworkerappsrunworkercompleted (object sender, RunWorkerCompletedEventArgs e)
{
If (e. Error! = Null)
{
MessageBox. Show (e. Error. Message );
}
Else if (e. Cancelled)
{
}
Else
{
}
}
Private void backgroundworker=dowork (object sender, DoWorkEventArgs e)
{
BackgroundWorker worker = sender as BackgroundWorker;
For (int I = 0; I <100; I ++)
{
This. dtAll = DBOperator. GetDataTable (""); // query data
Worker. ReportProgress (I );
If (worker. CancellationPending) // if the user cancels, the Data Processing code will pop out.
{
E. Cancel = true;
Break;
}
}
}
ProcessForm event (progress bar form)
Private BackgroundWorker backgroundWorker1;
Public ProcessForm (BackgroundWorker backgroundWorker1)
{
InitializeComponent ();
This. backgroundWorker1 = backgroundWorker1;
This. backgroundWorker1.ProgressChanged + = new ProgressChangedEventHandler (backgroundWorker1_ProgressChanged );
This. backgroundWorker1.RunWorkerCompleted + = new RunWorkerCompletedEventHandler (backgroundworkerappsrunworkercompleted );
}
Void backgroundworkerappsrunworkercompleted (object sender, RunWorkerCompletedEventArgs e)
{
This. Close ();
}
Void backgroundWorker1_ProgressChanged (object sender, ProgressChangedEventArgs e)
{
This. progressBar1.Value = e. ProgressPercentage;
}
Private void cancelbutton#click (object sender, EventArgs e)
{
This. backgroundWorker1.CancelAsync ();
This. cancelButton1.Enabled = false;
This. Close ();
}
For the complete source code, go to the group to download it.