As requested by a commenter/follower of the blog, I created an example which explains all most all the processes related to the Background worker in .Net. The processes from A - Z is explained as follows,
- Add a Background worker to the project
To add a background worker to the form you need, drag & drop the component from the Toolbox under the Components section.
- Allow to Report Current progress or Cancel the background operation
Set the WorkerReportsProgress and WorkerSupportsCancellation properties to "True" in-order to allow the Background worker to allow Report current progress or Cancel the current operation.
- Adding the DoWork, ProgressChanged and RunWorkerCompleted methods
DoWork method should include the background operation you intend to perform. In order to add this method you can select the background worker, go to events of it and double click on the DoWork. Using the same mechanism ProgressChanged and RunWorkerCompleted methods can be added as well.
- Implement the added methods
In the example I've composed the DoWork method includes a loop
which runs from 0 to 100. Also while the loop is running it is stopped
for 100 milliseconds at each iteration. The code segment is as follows,
private void backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
{
BackgroundWorker backWorker = sender as BackgroundWorker;
for (int i = 1; i <= 100; i++)
{
// Check wether the user has requested a cancellation,
// before processing further
if (!backWorker.CancellationPending)
{
// Wait 100 milliseconds
Thread.Sleep(100);
// Reports progress
backgroundWorker.ReportProgress(i);
}
else
e.Cancel = true;
}
}
As
seen on the above code segment, before continuing with each iteration it is checked the user has requested for a cancellation.
If so, the loop will be terminated. Also the current
progress of the background worker is reported. Then according to the
reported work progress, UI can be updated using the ProgressChanged method
as seen from the code below. I've updated the value of the progress bar
and a label displaying the current completed percentage.
private void backgroundWorker_ProgressChanged(object sender,
ProgressChangedEventArgs e)
{
// Setting the Progress bar value and updating the label
progressBar.Value = e.ProgressPercentage;
lblProgress.Text = string.Format(processingText,
e.ProgressPercentage.ToString());
}
private void backgroundWorker_ProgressChanged(object sender,
ProgressChangedEventArgs e)
{
// Setting the Progress bar value and updating the label
progressBar.Value = e.ProgressPercentage;
lblProgress.Text = string.Format(processingText,
e.ProgressPercentage.ToString());
}
After Completing or Cancelling the background process, RunWorkerCompleted method
will be executed which contains the finalizing section of the
background process. In this method you can perform a check whether the
process is cancelled or completed successfully and updated the UI
accordingly. Sample code is as follows,
private void backgroundWorker_RunWorkerCompleted(object sender,
RunWorkerCompletedEventArgs e)
{
// Checks wether the background process is cancelled
if (e.Cancelled)
lblProgress.Text = processCancelled;
else
lblProgress.Text = processCompleted;
progressBar.Value = 0;
errorProvider.Dispose();
}
private void backgroundWorker_RunWorkerCompleted(object sender,
RunWorkerCompletedEventArgs e)
{
// Checks wether the background process is cancelled
if (e.Cancelled)
lblProgress.Text = processCancelled;
else
lblProgress.Text = processCompleted;
progressBar.Value = 0;
errorProvider.Dispose();
}
After creating all the required methods all you need is to invoke the Background worker when needed. The invoking can be done as follows. A check is performed to see whether the background worker is busy or not before invoking which is a very important step.
private void btnPerfromBackOp_Click(object sender, EventArgs e)
{
// Checks if the Background worker is busy before giving a wake up call to it
if (!backgroundWorker.IsBusy)
{
//starts the background operation
backgroundWorker.RunWorkerAsync();
}
else
errorProvider.SetError(progressBar, backgroundWorkerBusy);
}
private void btnPerfromBackOp_Click(object sender, EventArgs e)
{
// Checks if the Background worker is busy before giving a wake up call to it
if (!backgroundWorker.IsBusy)
{
//starts the background operation
backgroundWorker.RunWorkerAsync();
}
else
errorProvider.SetError(progressBar, backgroundWorkerBusy);
}
The user is able to terminate a background process as well. To perform this the following code can be used in an event as desired. In this example I've used a button click event.
private void btnCancel_Click(object sender, EventArgs e)
{
if (backgroundWorker.WorkerSupportsCancellation)
{
// Requests the background process to stop
backgroundWorker.CancelAsync();
}
}
The following image displays the UI created for the above used example.
To download the sample follow the link below.
Background Worker Sample
Hope this post solves problems you have related to the Background worker. !!!
wow... you have explained it very clearly. Thanks alot. Keep it up.
ReplyDelete