RunWorkerAsync - The UI thread (the main program) should call this method to start the worker.
DoWork - The DoWork event is where the worker should do its work. It should periodically check its CancellationPending property to see if the UI thread is trying to stop it. If the worker is stopped, it should set the event's e.Cancel property to true.
CancelAsync - The UI thread can call this method to tell worker to stop. This sets the worker's CancellationPending to true.
ReportProgress - The worker can call this method to pass progress information back to the UI thread.
ProgressChanged - This event occurs when the worker calls ReportProgress. The UI thread can update labels, progress bars, and so forth to report progress to the user.
RunWorkerCompleted - This event occurs when the worker's DoEvent event handler ends. The UI thread can take action to clean up here. The e.Cancelled property tells whether the worker finished or was stopped.
The code for this example is relatively straightforward. Refer to the previous list as you look through the following code to see what each piece is supposed to do.
// Use the BackgroundWorker to perform a long task. private void btnGo_Click(object sender, EventArgs e) { if (btnGo.Text == "Go") { // Start the process. lblStatus.Text = "Working..."; btnGo.Text = "Stop"; prgPercentComplete.Value = 0; prgPercentComplete.Visible = true;
// Start the BackgroundWorker. bgwLongTask.RunWorkerAsync(); } else { // Stop the process. bgwLongTask.CancelAsync(); } }
// Perform the long task. private void bgwLongTask_DoWork(object sender, DoWorkEventArgs e) { // Spend 10 seconds doing nothing. for (int i = 1; i <= 10; i++) { // If we should stop, do so. if (bgwLongTask.CancellationPending) { // Indicate that the task was canceled. e.Cancel = true; break; }
// Sleep. System.Threading.Thread.Sleep(1000);
// Notify the UI thread of our progress. bgwLongTask.ReportProgress(i * 10); } }
// Update the progress bar. private void bgwLongTask_ProgressChanged(object sender, ProgressChangedEventArgs e) { prgPercentComplete.Value = e.ProgressPercentage; }
// The long task is done. private void bgwLongTask_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) { if (e.Cancelled) { lblStatus.Text = "Canceled"; } else { lblStatus.Text = "Finished"; } btnGo.Text = "Go"; prgPercentComplete.Visible = false; }
Comments