C Sharp TutorialC Sharp .NET Compiler Platform (Roslyn)C Sharp 3.0 FeaturesC Sharp 4.0 FeaturesC Sharp 5.0 FeaturesC Sharp 6.0 FeaturesC Sharp 7.0 FeaturesC Sharp Access ModifiersC Sharp Access network shared folder with username and passwordC Sharp Accessing DatabasesC Sharp Action FiltersC Sharp Aliases of built-in typesC Sharp an overview of collectionsC Sharp Anonymous typesC Sharp ArraysC Sharp ASP.NET IdentityC Sharp AssemblyInfo.cs ExamplesC Sharp Async-AwaitC Sharp Async/await, Backgroundworker, Task and Thread ExamplesC Sharp Asynchronous SocketC Sharp AttributesC Sharp Authentication handlerC Sharp BackgroundWorkerC Sharp BigIntegerC Sharp Binary SerializationC Sharp BindingListC Sharp Built-in TypesC Sharp CachingC Sharp CastingC Sharp Checked and UncheckedC Sharp CLSCompliantAttributeC Sharp Code ContractsC Sharp Code Contracts and AssertionsC Sharp Collection InitializersC Sharp Comments and regionsC Sharp Common String OperationsC Sharp Conditional StatementsC Sharp Constructors and FinalizersC Sharp Creating Own MessageBox in Windows Form ApplicationC Sharp Creational Design PatternsC Sharp Cryptography (System.Security.Cryptography)C Sharp Data AnnotationC Sharp DateTime MethodsC Sharp DelegatesC Sharp Dependency InjectionC Sharp DiagnosticsC Sharp Dynamic typeC Sharp EnumC Sharp Equality OperatorC Sharp Equals and GetHashCodeC Sharp EventsC Sharp Exception HandlingC Sharp Expression TreesC Sharp Extension MethodsC Sharp File and Stream I/OC Sharp FileSystemWatcherC Sharp Func delegatesC Sharp Function with multiple return valuesC Sharp Functional ProgrammingC Sharp Garbage Collector in .NETC Sharp Generating Random NumbersC Sharp Generic Lambda Query BuilderC Sharp GenericsC Sharp Getting Started: Json with C SharpC Sharp GuidC Sharp Handling FormatException when converting string to other typesC Sharp Hash FunctionsC Sharp ICloneableC Sharp IComparableC Sharp IDisposable interfaceC Sharp IEnumerableC Sharp ILGeneratorC Sharp ImmutabilityC Sharp Implementing Decorator Design PatternC Sharp Implementing Flyweight Design PatternC Sharp Import Google ContactsC Sharp Including Font ResourcesC Sharp IndexerC Sharp InheritanceC Sharp Initializing PropertiesC Sharp INotifyPropertyChanged interfaceC Sharp InterfacesC Sharp InteroperabilityC Sharp IQueryable interfaceC Sharp IteratorsC Sharp KeywordsC Sharp Lambda expressionsC Sharp Lambda ExpressionsC Sharp LINQ QueriesC Sharp LINQ to Objects

C Sharp BackgroundWorker

From WikiOD

Syntax[edit | edit source]

  • bgWorker.CancellationPending //returns whether the bgWorker was cancelled during its operation
  • bgWorker.IsBusy //returns true if the bgWorker is in the middle of an operation
  • bgWorker.ReportProgress(int x) //Reports a change in progress. Raises the "ProgressChanged" event
  • bgWorker.RunWorkerAsync() //Starts the BackgroundWorker by raising the "DoWork" event
  • bgWorker.CancelAsync() //instructs the BackgroundWorker to stop after the completion of a task.

Remarks[edit | edit source]

Performing long-running operations within the UI thread can cause your application to become unresponsive, appearing to the user that it has stopped working. It is preferred that these tasks be run on a background thread. Once complete, the UI can be updated.

Making changes to the UI during the BackgroundWorker's operation requires invoking the changes to the UI thread, typically by using the Control.Invoke method on the control you are updating. Neglecting to do so will cause your program to throw an exception.

The BackgroundWorker is typically only used in Windows Forms applications. In WPF applications, Tasks are used to offload work onto background threads (possibly in combination with async/await). Marshalling updates onto the UI thread is typically done automatically, when the property being updated implements INotifyPropertyChanged, or manually by using the UI thread's Dispatcher.

Using a BackgroundWorker to complete a task.[edit | edit source]

The following example demonstrates the use of a BackgroundWorker to update a WinForms ProgressBar. The backgroundWorker will update the value of the progress bar without blocking the UI thread, thus showing a reactive UI while work is done in the background.

namespace BgWorkerExample
    public partial class Form1 : Form

    //a new instance of a backgroundWorker is created.
    BackgroundWorker bgWorker = new BackgroundWorker();

    public Form1()

        prgProgressBar.Step = 1;

        //this assigns event handlers for the backgroundWorker
        bgWorker.DoWork += bgWorker_DoWork;
        bgWorker.RunWorkerCompleted += bgWorker_WorkComplete;

        //tell the backgroundWorker to raise the "DoWork" event, thus starting it.
        //Check to make sure the background worker is not already running.


    private void bgWorker_DoWork(object sender, DoWorkEventArgs e)
        //this is the method that the backgroundworker will perform on in the background thread.
        /* One thing to note! A try catch is not necessary as any exceptions will terminate the backgroundWorker and report 
          the error to the "RunWorkerCompleted" event */

    private void bgWorker_WorkComplete(object sender, RunWorkerCompletedEventArgs e)
        //e.Error will contain any exceptions caught by the backgroundWorker
        if (e.Error != null)
            MessageBox.Show("Task Complete!");
            prgProgressBar.Value = 0;

    // example method to perform a "long" running task.
    private void CountToY()
        int x = 0;

        int maxProgress = 100;
        prgProgressBar.Maximum = maxProgress;

        while (x < maxProgress)
            Invoke(new Action(() => { prgProgressBar.PerformStep(); }));
            x += 1;


The result is the following...[edit | edit source]

BackgroundWorker BackgroundWorker

Assigning Event Handlers to a BackgroundWorker[edit | edit source]

Once the instance of the BackgroundWorker has been declared, it must be given properties and event handlers for the tasks it performs.

    /* This is the backgroundworker's "DoWork" event handler. This 
       method is what will contain all the work you 
       wish to have your program perform without blocking the UI. */

    bgWorker.DoWork += bgWorker_DoWork;

    /*This is how the DoWork event method signature looks like:*/
    private void bgWorker_DoWork(object sender, DoWorkEventArgs e)
        // Work to be done here   
        // ...
        // To get a reference to the current Backgroundworker:
        BackgroundWorker worker = sender as BackgroundWorker;
        // The reference to the BackgroundWorker is often used to report progress

    /*This is the method that will be run once the BackgroundWorker has completed its tasks */

    bgWorker.RunWorkerCompleted += bgWorker_CompletedWork;

    /*This is how the RunWorkerCompletedEvent event method signature looks like:*/
    private void bgWorker_CompletedWork(object sender, RunWorkerCompletedEventArgs e)
        // Things to be done after the backgroundworker has finished

   /* When you wish to have something occur when a change in progress 
     occurs, (like the completion of a specific task) the "ProgressChanged" 
     event handler is used. Note that ProgressChanged events may be invoked
     by calls to bgWorker.ReportProgress(...) only if bgWorker.WorkerReportsProgress
     is set to true.  */

     bgWorker.ProgressChanged += bgWorker_ProgressChanged;

    /*This is how the ProgressChanged event method signature looks like:*/
    private void bgWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
        // Things to be done when a progress change has been reported

        /* The ProgressChangedEventArgs gives access to a percentage,
         allowing for easy reporting of how far along a process is*/
        int progress = e.ProgressPercentage;

Creating a new BackgroundWorker instance[edit | edit source]

A BackgroundWorker is commonly used to perform tasks, sometimes time consuming, without blocking the UI thread.

// BackgroundWorker is part of the ComponentModel namespace.
using System.ComponentModel;

namespace BGWorkerExample 
     public partial class ExampleForm : Form 

      // the following creates an instance of the BackgroundWorker named "bgWorker"
      BackgroundWorker bgWorker = new BackgroundWorker();

      public ExampleForm() { ...

Assigning Properties to a BackgroundWorker[edit | edit source]

This allows the BackgroundWorker to be cancelled in between tasks

bgWorker.WorkerSupportsCancellation = true;

This allows the worker to report progress between completion of tasks...

bgWorker.WorkerReportsProgress = true;

//this must also be used in conjunction with the ProgressChanged event