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:
- 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.
- BackgroundWorker backgroundWorker1 = new BackgroundWorker();
-
- private void btnStart_Click(object sender, EventArgs e)
- {
- backgroundWorker1.RunWokerAsync();
- }
-
- private void backgroundWorker1_DoWork(object sender, DoWorkeventArgs e)
- {
-
- Thread.Sleep(5000);
- }
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.
- BackgroundWorker backgroundWorker1 = new BackgroundWorker();
-
- private void btnStart_Click(object sender, EventArgs e)
- {
- backgroundWorker1.RunWokerAsync(2000);
- }
-
- private void backgroundWorker1_DoWork(object sender, DoWorkeventArgs e)
- {
- int input = (int)e.Argument;
-
- Thread.Sleep(input);
- }
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.
- BackgroundWorker backgroundWorker1 = new BackgroundWorker();
- backgroundWorker1.WorkerReportsProgress = true;
-
- private void btnStart_Click(object sender, EventArgs e)
- {
- backgroundWorker1.RunWokerAsync();
- }
-
- private void backgroundWorker1_DoWork(object sender, DoWorkeventArgs e)
- {
-
- for (int i = 1; i < 11; i++)
- {
- Thread.Sleep(2000);
- backgroundWorker1.ReportProgress(i*10);
- }
- }
- private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
- {
- progressBar1.value = e.ProgressPercentage;
- }
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.
- BackgroundWorker backgroundWorker1 = new BackgroundWorker();
- backgroundWorker1.WorkerSupportsCancellation = true;
-
- private void btnStart_Click(object sender, EventArgs e)
- {
- backgroundWorker1.RunWokerAsync();
- }
-
- private void btnCancel_Click(object sender, EventArgs e)
- {
- backgroundWorker1.CancelAsync();
- }
-
- private void backgroundWorker1_DoWork(object sender, DoWorkeventArgs e)
- {
-
- for (int i = 1; i < 11; i++)
- {
- Thread.Sleep(2000);
- backgroundWorker1.ReportProgress(i*10);
- if(backgroundWorker1.CancellationPending)
- {
- e.cancel = true;
- return;
- }
- }
- }
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.
- BackgroundWorker backgroundWorker1 = new BackgroundWorker();
-
- private void btnStart_Click(object sender, EventArgs e)
- {
- backgroundWorker1.RunWokerAsync();
- }
-
- private void btnCancel_Click(object sender, EventArgs e)
- {
- backgroundWorker1.CancelAsync();
- }
-
- private void backgroundWorker1_DoWork(object sender, DoWorkeventArgs e)
- {
-
- for (int i = 1; i < 11; i++)
- {
- Thread.Sleep(2000);
- backgroundWorker1.ReportProgress(i*10);
- if (backgroundWorker1.CancellationPending)
- {
- e.Cancel = true;
- return;
- }
- }
- }
- private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
- {
- if(e.Cancelled)
- {
- MessageBox.Show("Operation Cancelled");
- }
- else
- {
- MessageBox.Show("OperationCompleted");
- }
- }
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.
- BackgroundWorker backgroundWorker1 = new BackgroundWorker();
-
- private void btnStart_Click(object sender, EventArgs e)
- {
- backgroundWorker1.RunWokerAsync();
- }
-
- private void backgroundWorker1_DoWork(object sender, DoWorkeventArgs e)
- {
-
- Thread.Sleep(2000);
-
- e.Result = 10;
- }
- private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
- {
-
- int returnValue = (int)e.Result;
- }
you can see the full code of these examples after downloading the files with this article.