Using BackgroundWorker in C#
BackgroundWorker has three event handlers which basically take care of everything one needs to make it work.
- DoWork : The DoWork event handler is where the time consuming operation runs on the background thread.
- ProgressChanged : The ProgressChanged event handler is where we write code to update the user interface elements with the progress made so far.
- RunWorkerCompleted : Gets called when BackgroundWorker has completed the task.
So let's see how to use BackgroundWorer, create this Windows Forms application which start a process and cancel it, and displays the progression of the process in ProgressBar and in a label:
Add two buttons, a ProgressBar, and a label.Then drag a BackgroundWorker component from Toolbox:
Then set its WorkerSupportsCancellation, WorkerReportsProgress properties to True.
Also don't forget to add this directive:
using System.Threading;
- In backgroundWorker1 DoWork event add this code:
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
int sum = 0;
for (int i = 1; i <= 100; i++)
{
Thread.Sleep(100);
sum = sum + i;
backgroundWorker1.ReportProgress(i);
if (backgroundWorker1.CancellationPending)
{
e.Cancel = true;
backgroundWorker1.ReportProgress(0);
return;
}
}
e.Result = sum;
}
- backgroundWorker1 ProgressChanged event:
private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
progressBar1.Value = e.ProgressPercentage;
label1.Text = e.ProgressPercentage.ToString() + "%";
}
- backgroundWorker1 RunWorkerCompleted event:
private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if (e.Cancelled)
{
label1.Text = "Operation cancelled";
}
else if (e.Error != null)
{
label1.Text = e.Error.Message;
}
else
{
label1.Text = e.Result.ToString();
}
}
- StartButton click event:
private void StartButton_Click(object sender, EventArgs e)
{
if (!backgroundWorker1.IsBusy)
{
backgroundWorker1.RunWorkerAsync();
}
}
backgroundWorker1.RunWorkerAsync() method will start the execution of the operation asynchronously in the background
- CancelButton click event:
private void CancelButton_Click(object sender, EventArgs e)
{
if (backgroundWorker1.IsBusy)
{
backgroundWorker1.CancelAsync();
}
}
backgroundWorker1.CancelAsync() method will cancel the asynchronous operation if still in progress.
Using BackgroundWorker in C#
Reviewed by Bloggeur DZ
on
03:27
Rating:
Aucun commentaire: