blog

Home / DeveloperSection / Blogs / How to use backgroundWorker Class in C#

How to use backgroundWorker Class in C#

Vijay Shukla7153 08-Jun-2013

In this blog I am trying to explain how to use backgroundWorker class in C#.

Backgroundworker

The Backgroundworker class provides a simple approach to run time-consuming operations on a background thread. The Backgroundworker class enables you to check the state of the operation and it lets you cancel the operation.

When using of the Backgroundworker class, you can point to operation progress, completion, and cancellation. For example, you can check whether the background operation is completed or canceled and display a message to the user.

Hoe to o use the Backgroundworker class: -

1.       Create an instance of the Backgroundworker class.

a.       Backgroundworker _ backgroundworker = new Backgroundworker();

2.       Write the below code where which you want to background operation to allow cancellation and to report progress.

b.      _ backgroundworker.WorkerSupportsCancellation = true;

c.       _ backgroundworker.WorkerReportsProgress = true;

3.       Create an event handler for the background worker's DoWork event. This event is raised when you call the RunWorkerAsync method.

private void _backgroundworker_DoWork(object sender, DoWorkEventArgs e)
{
}

4.       Create an event handler for the background worker's ProgressChanged event. In this event add code to indicate the progress. This event is raised when you call the ReportProgress method.

private void _backgroundworker_ProgressChanged(object sender, ProgressChangedEventArgs e) 
{
}

5. Create an event handler for the RunWorkerCompleted event. This event is raised when the DoWork event handler returns.

private void _backgroundworker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) 
{
 }

Example: -
using System.ComponentModel;
using System.Windows;
using System.Windows.Controls;

namespace My_BackgroundWorker_CS
{
    public partial class Page : UserControl
    {
        private BackgroundWorker _backgroundworker = new BackgroundWorker();
        public Page()
        {
            InitializeComponent();

            _backgroundworker.WorkerReportsProgress = true;
            _backgroundworker.WorkerSupportsCancellation = true;
            _backgroundworker.DoWork += new DoWorkEventHandler(bw_DoWork);
            _backgroundworker.ProgressChanged += new ProgressChangedEventHandler(bw_ProgressChanged);             _backgroundworker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bw_RunWorkerCompleted);
        }
        private void buttonStart_Click(object sender, RoutedEventArgs e)
        {
            if (_backgroundworker.IsBusy != true)
            {
                _backgroundworker.RunWorkerAsync();
            }
        }
        private void buttonCancel_Click(object sender, RoutedEventArgs e)
        {
            if (_backgroundworker.WorkerSupportsCancellation == true)
            {
                _backgroundworker.CancelAsync();
            }
        }
        private void bw_DoWork(object sender, DoWorkEventArgs e)
        {
            BackgroundWorker worker = sender as BackgroundWorker;
            for (int i = 1; (i <= 10); i++)
            {
                if ((worker.CancellationPending == true))
                {
                    e.Cancel = true;
                    break;
                }
                else
                {
                    System.Threading.Thread.Sleep(500);
                    worker.ReportProgress((i * 10));
                }
            }
        }
        private void bw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)         {
            if ((e.Cancelled == true))
            {
                this.tbProgress.Text = "Canceled!";
            }
            else if (!(e.Error == null))
            {
                this.tbProgress.Text = ("Error: " + e.Error.Message);
            }
            else
            {
                this.tbProgress.Text = "Done!";
            }
        }
        private void bw_ProgressChanged(object sender, ProgressChangedEventArgs e)         {
            this.tbProgress.Text = (e.ProgressPercentage.ToString() + "%");
        }
    }
}


Updated 18-Sep-2014

Leave Comment

Comments

Liked By