Use a BackgroundWorker to perform a task in the background in C#

The example Use multiple threads to let a program draw a graph and perform other tasks at the same time in C# lets you perform an action in the background. Unfortunately using threads directly can be confusing.

The BackgroundWorker component provides a slightly easier way to perform a background task.

The key pieces to the BackgroundWorker are:

  • 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;
}

   

 

What did you think of this article?




Trackbacks
  • No trackbacks exist for this post.
Comments
  • No comments exist for this post.
Leave a comment

Submitted comments are subject to moderation before being displayed.

 Name

 Email (will not be published)

 Website

Your comment is 0 characters limited to 3000 characters.