Using the BackgroundWorker component

Introduction

The BackgroundWorker allows you to execute operations that take a long period of time such as database transaction or file downloads, asynchronously on a separate thread and allow the user interface to remain responsive.

Start an Operation in the Background

First, you need to add an instance of the BackgroundWorker component to your application, if you use visual studio, just drag it from the toolbox to your application or you can create it manually as follow:

  1. BackgroundWorker backgroundWorker1 = new BackgroundWorker();  
To start the operation in the background you have to call the RunWorkerAsync() method of the BackgroundWorker, when you call this method the BackgroundWroker starts the execution of the background operation by raising the DoWork event, the code in the DoWork event handler is executed on a separate thread.
  1. BackgroundWorker backgroundWorker1 = new BackgroundWorker();  
  2. //start the operation on another thread  
  3. private void btnStart_Click(object sender, EventArgs e)  
  4. {  
  5.     backgroundWorker1.RunWokerAsync();  
  6. }  
  7. //DoWork event handler is executed on a separate thread  
  8. private void backgroundWorker1_DoWork(object sender, DoWorkeventArgs e)  
  9. {  
  10.     //a long running operation  
  11.     Thread.Sleep(5000);  
  12. }  
You can send a parameter to the background operation using the RunWorkerAsync() method. You can receive this parameter by using the Argument property of the instance of DoWorkEventArgs in the DoWork event handler then you cast it to use it in the background operation.
  1. BackgroundWorker backgroundWorker1 = new BackgroundWorker();  
  2. //start the operation on another thread  
  3. private void btnStart_Click(object sender, EventArgs e)  
  4. {  
  5.     backgroundWorker1.RunWokerAsync(2000);  
  6. }  
  7. //DoWork event handler is executed on a separate thread  
  8. private void backgroundWorker1_DoWork(object sender, DoWorkeventArgs e)  
  9. {  
  10.     int input = (int)e.Argument;  
  11.     //a long running operation  
  12.     Thread.Sleep(input);  
  13. }  
Reporting progress of a background operation using BackgroundWorker

By using the BackgroundWorker you have the ability to report progress updates of the executing operation. To use this options you must set the WorkerReportsProgress to true.

To start report progress you call ReportProgress() method and use it to pass a parameter that have the value of the percentage of the progress that have been completed. This method raises the BackgroundWorker.ProgressChanged event. In the event handler of the ProgressChanged you can recieve the value of the progress precentage on the main thread using the ProgressPercentage property of the instance of ProgressChangedEventArgs.

  1. BackgroundWorker backgroundWorker1 = new BackgroundWorker();  
  2. backgroundWorker1.WorkerReportsProgress = true;  
  3. //start the operation on another thread  
  4. private void btnStart_Click(object sender, EventArgs e)  
  5. {  
  6.     backgroundWorker1.RunWokerAsync();  
  7. }  
  8. //DoWork event handler is executed on a separate thread  
  9. private void backgroundWorker1_DoWork(object sender, DoWorkeventArgs e)  
  10. {  
  11.     //a long running operation  
  12.     for (int i = 1; i < 11; i++)  
  13.     {     
  14.         Thread.Sleep(2000);  
  15.         backgroundWorker1.ReportProgress(i*10);  
  16.     }  
  17. }  
  18. private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)  
  19. {  
  20.     progressBar1.value = e.ProgressPercentage;  
  21. }  
Canceling a background operation using BackgroundWorker

With the BackgroundWorker you have the ability to cancel the background operation, to do this you first must set WorkerSupportsCancellation property to true.

The next step is to call the CancelAsync() method by doing so you set the CancellationPending property to true, by polling the CancellationPending property you can determine whether or not to cancel the background operation.

  1. BackgroundWorker backgroundWorker1 = new BackgroundWorker();  
  2. backgroundWorker1.WorkerSupportsCancellation = true;  
  3. //start the operation on another thread  
  4. private void btnStart_Click(object sender, EventArgs e)  
  5. {  
  6.     backgroundWorker1.RunWokerAsync();  
  7. }  
  8. //a buttun to cancel the operation  
  9. private void btnCancel_Click(object sender, EventArgs e)  
  10. {  
  11.     backgroundWorker1.CancelAsync();  
  12. }  
  13. //DoWork event handler is executed on a separate thread  
  14. private void backgroundWorker1_DoWork(object sender, DoWorkeventArgs e)  
  15. {  
  16.     //a long running operation  
  17.     for (int i = 1; i < 11; i++)  
  18.     {  
  19.         Thread.Sleep(2000);  
  20.         backgroundWorker1.ReportProgress(i*10);  
  21.         if(backgroundWorker1.CancellationPending)  
  22.         {  
  23.             e.cancel = true;  
  24.             return;  
  25.         }  
  26.     }  
  27. }  
Alert the user in the completion of the background operation

When the background operation completes, whether because the background operation is completed or canceled, the RunWorkerCompleted event is raised. You can alert the user to the completion by handling the RunWorkerCompleted event.

You can determine if the user canceled the operation by using the Cancelled property of the instance RunWorkerCompletedEventArgs.

  1. BackgroundWorker backgroundWorker1 = new BackgroundWorker();  
  2. //start the operation on another thread  
  3. private void btnStart_Click(object sender, EventArgs e)  
  4. {  
  5.     backgroundWorker1.RunWokerAsync();  
  6. }  
  7. //a buttun to cancel the operation  
  8. private void btnCancel_Click(object sender, EventArgs e)  
  9. {  
  10.     backgroundWorker1.CancelAsync();  
  11. }   
  12. //DoWork event handler is executed on a separate thread  
  13. private void backgroundWorker1_DoWork(object sender, DoWorkeventArgs e)  
  14. {  
  15.     //a long running operation  
  16.     for (int i = 1; i < 11; i++)  
  17.     {  
  18.         Thread.Sleep(2000);  
  19.         backgroundWorker1.ReportProgress(i*10);  
  20.         if (backgroundWorker1.CancellationPending)  
  21.         {  
  22.             e.Cancel = true;  
  23.             return;  
  24.         }  
  25.     }  
  26. }   
  27. private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)  
  28. {  
  29.     if(e.Cancelled)  
  30.     {  
  31.         MessageBox.Show("Operation Cancelled");  
  32.     }  
  33.     else  
  34.     {  
  35.         MessageBox.Show("OperationCompleted");  
  36.     }  
  37. }  
Return a value from the background operation

You can return a value from the background operation that in the DoWork event handler using the Result property of the DoWorkEventArgs instance, and you can receive it in the RunWorkerCompleted event handler using the Result property of the RunWorkerCompletedEventArgs instance.

  1. BackgroundWorker backgroundWorker1 = new BackgroundWorker();  
  2. //start the operation on another thread  
  3. private void btnStart_Click(object sender, EventArgs e)  
  4. {  
  5.     backgroundWorker1.RunWokerAsync();  
  6. }  
  7. //DoWork event handler is executed on a separate thread  
  8. private void backgroundWorker1_DoWork(object sender, DoWorkeventArgs e)  
  9. {  
  10.     //a long running operation here  
  11.     Thread.Sleep(2000);  
  12.     //return the value here  
  13.     e.Result = 10;  
  14. }  
  15. private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)  
  16. {  
  17.     //recieve the return value here  
  18.     int returnValue = (int)e.Result;  
  19. }  
you can see the full code of these examples after downloading the files with this article.


Similar Articles