Click here to Skip to main content
15,867,594 members
Articles / Desktop Programming / Windows Forms

BackgroundWorker Class Sample for Beginners

Rate me:
Please Sign up or sign in to vote.
4.93/5 (104 votes)
4 Aug 2010CPOL4 min read 539.7K   21.2K   180   54
Simple steps to a Multithreaded application

Introduction

This article presents a novice .NET developer to develop a multithreading application without being burdened by the complexity that comes with threading.

Background

A basic Windows application runs on a single thread usually referred to as UI thread. This UI thread is responsible for creating/painting all the controls and upon which the code execution takes place. So when you are running a long-running task (i.e., data intensive database operation or processing some 100s of bitmap images), the UI thread locks up and the UI application turns white (remember the UI thread was responsible to paint all the controls) rendering your application to Not Responding state.

Basic.PNG

Using the Code

What you need to do is to shift this heavy processing on a different thread.

ParallelTask.PNG

Leave the UI thread free for painting the UI. .NET has made the BackgroundWorker object available to us to simplify threading. This object is designed to simply run a function on a different thread and then call an event on your UI thread when it's complete.

The steps are extremely simple:

  1. Create a BackgroundWorker object.
  2. Tell the BackgroundWorker object what task to run on the background thread (the DoWork function).
  3. Tell it what function to run on the UI thread when the work is complete (the RunWorkerCompleted function).

BackgroundWorker uses the thread-pool, which recycles threads to avoid recreating them for each new task. This means one should never call Abort on a BackgroundWorker thread.

And a golden rule never to forget:

Never access UI objects on a thread that didn't create them. It means you cannot use a code such as this...

C#
lblStatus.Text = "Processing file...20%";

...in the DoWork function. Had you done this, you would receive a runtime error. The BackgroundWorker object resolves this problem by giving us a ReportProgress function which can be called from the background thread's DoWork function. This will cause the ProgressChanged event to fire on the UI thread. Now we can access the UI objects on their thread and do what we want (In our case, setting the label text status).

BackgroundWorker also provides a RunWorkerCompleted event which fires after the DoWork event handler has done its job. Handling RunWorkerCompleted is not mandatory, but one usually does so in order to query any exception that was thrown in DoWork. Furthermore, code within a RunWorkerCompleted event handler is able to update Windows Forms and WPF controls without explicit marshalling; code within the DoWork event handler cannot.

To add support for progress reporting:

  • Set the WorkerReportsProgress property to true.
  • Periodically call ReportProgress from within the DoWork event handler with a "percentage complete" value.
    C#
    m_oWorker.ReportProgress(i); //as seen in the code 
  • Handle the ProgressChanged event, querying its event argument's ProgressPercentage property:
    C#
    void m_oWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
    {
        // This function fires on the UI thread so it's safe to edit
        // the UI control directly, no funny business with Control.Invoke :)
        // Update the progressBar with the integer supplied to us from the
        // ReportProgress() function.
        progressBar1.Value = e.ProgressPercentage;
        lblStatus.Text = "Processing......" + progressBar1.Value.ToString() + "%";
    } 

Code in the ProgressChanged event handler is free to interact with UI controls just as with RunWorkerCompleted. This is typically where you will update a progress bar.

To add support for cancellation:

  • Set the WorkerSupportsCancellation property to true.
  • Periodically check the CancellationPending property from within the DoWork event handler – if true, set the event argument's Cancel property to true, and return. (The worker can set Cancel true and exit without prompting via CancellationPending – if it decides the job's too difficult and it can't go on).
    C#
    if (m_oWorker.CancellationPending)
     {
        // Set the e.Cancel flag so that the WorkerCompleted event
        // knows that the process was cancelled.
        e.Cancel = true;
        m_oWorker.ReportProgress(0);
        return;
     }
    
  • Call CancelAsync to request cancellation. This code is handled on click of the Cancel button.

    C#
    m_oWorker.CancelAsync();
    

Properties

This is not an exhaustive list, but I want to emphasize the Argument, Result, and the RunWorkerAsync methods. These are properties of BackgroundWorker that you absolutely need to know to accomplish anything. I show the properties as you would reference them in your code.

  • DoWorkEventArgs e Usage: Contains e.Argument and e.Result, so it is used to access those properties.
  • e.Argument Usage: Used to get the parameter reference received by RunWorkerAsync.
  • e.Result Usage: Check to see what the BackgroundWorker processing did.
  • m_oWorker.RunWorkerAsync(); Usage: Called to start a process on the worker thread.

Here's the entire code:

C#
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Threading;
using System.Text;
using System.Windows.Forms;

namespace BackgroundWorkerSample
{
    // The BackgroundWorker will be used to perform a long running action
    // on a background thread.  This allows the UI to be free for painting
    // as well as other actions the user may want to perform.  The background
    // thread will use the ReportProgress event to update the ProgressBar
    // on the UI thread.
    public partial class Form1 : Form
    {
        /// <summary>
        /// The backgroundworker object on which the time consuming operation 
        /// shall be executed
        /// </summary>
        BackgroundWorker m_oWorker;

        public Form1()
        {
            InitializeComponent();
            m_oWorker = new BackgroundWorker();
    
            // Create a background worker thread that ReportsProgress &
            // SupportsCancellation
            // Hook up the appropriate events.
            m_oWorker.DoWork += new DoWorkEventHandler(m_oWorker_DoWork);
            m_oWorker.ProgressChanged += new ProgressChangedEventHandler
					(m_oWorker_ProgressChanged);
            m_oWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler
					(m_oWorker_RunWorkerCompleted);
            m_oWorker.WorkerReportsProgress = true;
            m_oWorker.WorkerSupportsCancellation = true;
        }

        /// <summary>
        /// On completed do the appropriate task
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void m_oWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            // The background process is complete. We need to inspect
            // our response to see if an error occurred, a cancel was
            // requested or if we completed successfully.  
            if (e.Cancelled)
            {
                lblStatus.Text = "Task Cancelled.";
            }

            // Check to see if an error occurred in the background process.

            else if (e.Error != null)
            {
                lblStatus.Text = "Error while performing background operation.";
            }
            else
            {  
                // Everything completed normally.
                lblStatus.Text = "Task Completed...";
            }

            //Change the status of the buttons on the UI accordingly
            btnStartAsyncOperation.Enabled = true;
            btnCancel.Enabled = false;
        }

        /// <summary>
        /// Notification is performed here to the progress bar
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void m_oWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {

            // This function fires on the UI thread so it's safe to edit

            // the UI control directly, no funny business with Control.Invoke :)

            // Update the progressBar with the integer supplied to us from the

            // ReportProgress() function.  

            progressBar1.Value = e.ProgressPercentage;
            lblStatus.Text = "Processing......" + progressBar1.Value.ToString() + "%";
        }

        /// <summary>
        /// Time consuming operations go here </br>
        /// i.e. Database operations,Reporting
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void m_oWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            // The sender is the BackgroundWorker object we need it to
            // report progress and check for cancellation.
            //NOTE : Never play with the UI thread here...
            for (int i = 0; i < 100; i++)
            {
                Thread.Sleep(100);

                // Periodically report progress to the main thread so that it can
                // update the UI.  In most cases you'll just need to send an
                // integer that will update a ProgressBar                    
                m_oWorker.ReportProgress(i);
                // Periodically check if a cancellation request is pending.
                // If the user clicks cancel the line
                // m_AsyncWorker.CancelAsync(); if ran above.  This
                // sets the CancellationPending to true.
                // You must check this flag in here and react to it.
                // We react to it by setting e.Cancel to true and leaving
                if (m_oWorker.CancellationPending)
                {
                    // Set the e.Cancel flag so that the WorkerCompleted event
                    // knows that the process was cancelled.
                    e.Cancel = true;
                    m_oWorker.ReportProgress(0);
                    return;
                }
            }

            //Report 100% completion on operation completed
            m_oWorker.ReportProgress(100);
        }

        private void btnStartAsyncOperation_Click(object sender, EventArgs e)
        {
            //Change the status of the buttons on the UI accordingly
            //The start button is disabled as soon as the background operation is started
            //The Cancel button is enabled so that the user can stop the operation 
            //at any point of time during the execution
            btnStartAsyncOperation.Enabled = false;
            btnCancel.Enabled = true;

            // Kickoff the worker thread to begin it's DoWork function.
            m_oWorker.RunWorkerAsync();
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            if (m_oWorker.IsBusy)
            {

                // Notify the worker thread that a cancel has been requested.

                // The cancel will not actually happen until the thread in the

                // DoWork checks the m_oWorker.CancellationPending flag. 

                m_oWorker.CancelAsync();
            }
        }
    }
}

1. Start

Once the application is started, click on the button that reads Start Asynchronous Operation. The UI now shows a progressbar with UI continuously being updated.

Processing.PNG

2. Cancel

To cancel the parallel operation midway, press the cancel button. Note that the UI thread is now free to perform any additional task during this time and it is not locked by the data intensive operation that is happening in the background.

Cancelled.PNG

3. On Successful Completion

Completed.PNG

The statusbar shall read Task Completed upon the successful completion of the parallel task.

Points of Interest

History

  • 4th August, 2010: Initial version

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer Honeywell International
India India
Software Developer, Cinephile, Dromomaniac, Animal lover, Self proclaimed Photographer not necessarily in the same order.

Comments and Discussions

 
GeneralMy vote of 5 Pin
Member 140368386-Sep-20 0:56
Member 140368386-Sep-20 0:56 
GeneralMy vote of 5 Pin
Jim_Snyder19-Jul-18 4:08
professionalJim_Snyder19-Jul-18 4:08 
Question30 second long task, which cannot be divided. Pin
Member 1183741413-Dec-16 7:38
Member 1183741413-Dec-16 7:38 
QuestionNice Pin
RemyJaubert9-Nov-16 21:23
RemyJaubert9-Nov-16 21:23 
QuestionHelp with the thread + gui combo Pin
Member 126429142-Oct-16 2:52
Member 126429142-Oct-16 2:52 
AnswerRe: Help with the thread + gui combo Pin
Srivatsa Haridas2-Oct-16 18:15
professionalSrivatsa Haridas2-Oct-16 18:15 
QuestionPorting your code, I can't get it to work Pin
turbosupramk327-Sep-16 10:10
turbosupramk327-Sep-16 10:10 
AnswerRe: Porting your code, I can't get it to work Pin
Srivatsa Haridas2-Oct-16 18:12
professionalSrivatsa Haridas2-Oct-16 18:12 
QuestionHow can a method executed inside DoWork without repeating it through For Loop? Pin
el_serafi15-Feb-16 11:05
el_serafi15-Feb-16 11:05 
AnswerRe: How can a method executed inside DoWork without repeating it through For Loop? Pin
Srivatsa Haridas7-Mar-16 18:08
professionalSrivatsa Haridas7-Mar-16 18:08 
It is very difficult to understand what is that you're trying to achieve without looking at your code.
May be you can share your code so that I can comment on it. My first guess would be to refactor your code initially. However, as I said I need to look at your code first to understand.
QuestionA Question & Thank you! Pin
Member 120216528-Oct-15 19:38
Member 120216528-Oct-15 19:38 
AnswerRe: A Question & Thank you! Pin
Srivatsa Haridas11-Oct-15 18:45
professionalSrivatsa Haridas11-Oct-15 18:45 
GeneralRe: A Question & Thank you! Pin
Member 1202165211-Oct-15 19:15
Member 1202165211-Oct-15 19:15 
GeneralRe: A Question & Thank you! Pin
Srivatsa Haridas11-Oct-15 22:19
professionalSrivatsa Haridas11-Oct-15 22:19 
GeneralRe: A Question & Thank you! Pin
Member 1202165211-Oct-15 22:42
Member 1202165211-Oct-15 22:42 
QuestionGreat Job Pin
Ramesh Balasubramani23-Jun-15 2:23
Ramesh Balasubramani23-Jun-15 2:23 
GeneralMy vote of 5 Pin
Malhotra Sameer2-Jan-15 7:41
professionalMalhotra Sameer2-Jan-15 7:41 
GeneralNice Article, Guys do check TPL as next step Pin
Malhotra Sameer2-Jan-15 7:40
professionalMalhotra Sameer2-Jan-15 7:40 
GeneralMy vote of 4 Pin
Y Anil Kumar29-Oct-14 20:58
Y Anil Kumar29-Oct-14 20:58 
GeneralRe: My vote of 4 Pin
Srivatsa Haridas18-Mar-15 2:22
professionalSrivatsa Haridas18-Mar-15 2:22 
QuestionThank You! Pin
Rockie(aka Collapse Troll)24-Sep-14 3:49
Rockie(aka Collapse Troll)24-Sep-14 3:49 
QuestionVery well explained Pin
shaijujanardhanan31-Aug-14 5:02
shaijujanardhanan31-Aug-14 5:02 
QuestionVery Nice & Clearly Explained - Thanks Pin
_WinBase_30-Aug-14 5:35
_WinBase_30-Aug-14 5:35 
Questionwell done Pin
Harry Honeywell31-Jul-14 3:57
Harry Honeywell31-Jul-14 3:57 
QuestionNew to C# Pin
darksun696-Jul-14 23:15
darksun696-Jul-14 23:15 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.