Using BackgroundWorker in C#

The BackgroundWorker is a class in System.ComponentModel that allows you to run an operation on a separate, dedicated thread. Time-consuming operations like downloads and database transactions can cause your user interface (UI) to seem as though it has stopped responding while they are running. When you want a responsive UI and you are faced with long delays associated with such operations, the BackgroundWorker class provides a convenient solution.

BackgroundWorker has three event handlers which basically take care of everything one needs to make it work.
  1. DoWork : The DoWork event handler is where the time consuming operation runs on the background thread.
  2. ProgressChanged : The ProgressChanged event handler is where we write code to update the user interface elements with the progress made so far.
  3. 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.

Now, we run the application, we click START button:



We click CANCEL button:


To understand more, check out this video:





Using BackgroundWorker in C# Using BackgroundWorker in C# Reviewed by Bloggeur DZ on 03:27 Rating: 5

Aucun commentaire:

Fourni par Blogger.