C# using a background worker

This post is going to focus on creating and using a BackgroundWorker object. Background workers are found in the System.ComponentModel namespace. They're pretty easy to use. You just create a new object, assign a few properties and event handlers and let it do its thing.

using System;
using System.ComponentModel;

First let's create a background worked object and set it up.

Pstatic void Main( string[] args
{
   // create the background worker object
   BackgroundWorker _worker = new BackgroundWorker();

   // tell the background worker it can be cancelled and report progress
   _worker.WorkerReportsProgress = true;
   _worker.WorkerSupportsCancellation = true;

   // a worker thread object where the actual work happens
   WorkerThread thread = new WorkerThread();

   // add our event handlers
   _worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler( thread.RunWorkerCompleted );
   _worker.ProgressChanged += new ProgressChangedEventHandler( thread.ProgressChanged );
   _worker.DoWork += new DoWorkEventHandler( thread.DoWork );

   // start the worker thread
   _worker.RunWorkerAsync();

   // wait for it to be completed
   while( !_worker.CancellationPending )
   {
      // sleep for a second
      Thread.Sleep( 1000 );
    }

    Console.ReadKey();

}


There are two properties WorkerReportsProgress and WorkerSupportsCancellation. These are set to false by default. You will need to set them to true if you want to be able to get progress reports back from the worker or cancel it before the work is done.

Now the next section is a class that actually does the work. I called mine ThreadWorker but it can be anything.

public class WorkerThread
{
    public void DoWork( object sender, DoWorkEventArgs e )
    {
       //get a handle on the worker that started this request
       BackgroundWorker workerSender = sender as BackgroundWorker;

       // loop through 10 times and report the progress back to the sending object
       for( int i = 0; i < 10; i++ )
       {
          // tell the worker that we want to report progress being made
          workerSender.ReportProgress( i );
          Thread.Sleep( 100 );
       }

       // cancel the thread and send back that we cancelled
       workerSender.CancelAsync();
       e.Cancel = true;

    }

    public void RunWorkerCompleted( object sender, RunWorkerCompletedEventArgs e )
    {
       Console.WriteLine( "Worker Done!!" );          
    }

    public void ProgressChanged( object sender, ProgressChangedEventArgs e )
    {
      // print out the percent changed
      Console.WriteLine( e.ProgressPercentage );
    }
}

Notice the three methods correspond to the 3 event handlers above. When creating the BackgroundWorker you can tell it what methods to call for certain events. I prefer to use a class that is built specifically for those events.

So I hope this helps people figure out and use BackgroundWorker objects. I find them very handy especially in UI programming when I need to report on how much work is being done, etc. Or when I need to be able to know when a thread is done and have the ability to cancel it.

Comments

Popular posts from this blog

String.Replace vs Regex.Replace

C# Producer Consumer using Rabbit MQ

C# Form Application in Kiosk Mode/Fullscreen