Background Worker

Background Worker in C#

The BackgroundWorker class lets us perform a distinct thread operation. Time consuming activities, such as downloads and transactions in the database, can make our UI seem like it stops reacting while it is operating or not responding while they are running.

The class BackgroundWorker provides a convenient solution if we want a responsive UI, and have long delays with such operations.

Create a background worker to perform a time consuming operation and Listen to events that report our operation progress and signal when our operation is completed. We can programmatically create the BackgroundWorker or from the Components tab of the Toolbox we can drag it on to our form.

If we are using Windows Form Designer to create the background worker, In the Component Tray it will appear, and its properties in the Properities window will be shown.

Background Worker in C#

 

Add an event handler for the DoWork event in order to set up a background operation. Call this event handler for our time-consuming procedure. Call RunWorkerAsync to begin the process. ProgressChanged event is managed to receive progress updates notifications. The RunWorkerCompleted event is handled to obtain the notification when the process is finished.

Note: In our DoWork event handler, we need to take care not to manipulate any user-interface object. Instead, communicate via ProgressChanged and RunWorkerCompleted events to the user interface.

If a parameter requires our background operation, call RunWorkerAsync with our parameter. We can extract the parameter in the DoWorkEventArgs. Argument property within the event handler.

 

Example:

The following code example shows the basics of the BackgroundWorker class for the asynchronous execution of a time consuming operation.

  1. Create an application with Windows Forms.
  2. Add a Label control named lblResult and add two Button controls named btnStartAsync and btnCancelAsync.
  3. For both buttons create Click Event handler.
  4. Add Progressbar and name it progressbar1.
  5. From the Toolbox, add a BackgroundWorker component named backgroundWorker1.
  6. Create DoWork, ProgressChanged, and RunWorkerCompleted event handlers for the BackgroundWorker.

 

Background Worker in C#

First of all true to following background property


 backgroundWorker1.WorkerReportsProgress = true;
 backgroundWorker1.WorkerSupportsCancellation = true;

 

Double click on start button and write following code


private void BtnStartAsync_Click(object sender, EventArgs e)
        {
            if (backgroundWorker1.IsBusy != true)
            {
                // Start the asynchronous operation.
                backgroundWorker1.RunWorkerAsync();
            }
        }

Double click on cancel button and write following code


 if (backgroundWorker1.WorkerSupportsCancellation == true)
            {
                // Cancel the asynchronous operation.
                backgroundWorker1.CancelAsync();
            }

The DoWork event handler looks like this where we need to call our time-consuming approach.


private void BackgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            // This event handler is where the time-consuming work is done.
            BackgroundWorker worker = sender as BackgroundWorker;

            for (int i = 1; i <= 10; i++)
            {
                if (worker.CancellationPending == true)
                {
                    e.Cancel = true;
                    break;
                }
                else
                {
                    // Perform a time consuming operation and report progress.
                    System.Threading.Thread.Sleep(500);
                    worker.ReportProgress(i * 10);
                }
            }

        }

Write the following code for ProgressChanged event.


 private void BackgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            progressBar1.Value = e.ProgressPercentage;
            lblResult.Text = (e.ProgressPercentage.ToString() + "%");
        }

Write the following code for ProgressChanged event.


 private void BackgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if (e.Cancelled == true)
            {
                lblResult.Text = "Canceled!";
            }
            else if (e.Error != null)
            {
                lblResult.Text = "Error: " + e.Error.Message;
            }
            else
            {
                lblResult.Text = "Done!";
            }
        }

Complete Source Code


using System;
using System.ComponentModel;
using System.Windows.Forms;

namespace BackgroundWorkerControl
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            backgroundWorker1.WorkerReportsProgress = true;
            backgroundWorker1.WorkerSupportsCancellation = true;
        }

        private void BackgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            // This event handler is where the time-consuming work is done.
            BackgroundWorker worker = sender as BackgroundWorker;

            for (int i = 1; i <= 10; i++)
            {
                if (worker.CancellationPending == true)
                {
                    e.Cancel = true;
                    break;
                }
                else
                {
                    // Perform a time consuming operation and report progress.
                    System.Threading.Thread.Sleep(500);
                    worker.ReportProgress(i * 10);
                }
            }

        }

        private void BackgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            progressBar1.Value = e.ProgressPercentage;
            lblResult.Text = (e.ProgressPercentage.ToString() + "%");
        }

        private void BackgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if (e.Cancelled == true)
            {
                lblResult.Text = "Canceled!";
            }
            else if (e.Error != null)
            {
                lblResult.Text = "Error: " + e.Error.Message;
            }
            else
            {
                lblResult.Text = "Done!";
            }
        }

        private void BtnStartAsync_Click(object sender, EventArgs e)
        {
            if (backgroundWorker1.IsBusy != true)
            {
                // Start the asynchronous operation.
                backgroundWorker1.RunWorkerAsync();
            }
        }

        private void BtnCancelAsync_Click(object sender, EventArgs e)
        {
            if (backgroundWorker1.WorkerSupportsCancellation == true)
            {
                // Cancel the asynchronous operation.
                backgroundWorker1.CancelAsync();
            }
        }
    }
}

Download Source Code In C#