Posted by: R Manimaran | July 9, 2008

BackgroundWorker in C# Threading

BackgroundWorker is a helper class in the System.ComponentModel namespace for managing a worker thread. It provides the following features:

  • A “cancel” flag for signaling a worker to end without using Abort
  • A standard protocol for reporting progress, completion and cancellation
  • An implementation of IComponent allowing it be sited in the Visual Studio Designer
  • Exception handling on the worker thread
  • The ability to update Windows Forms and WPF controls in response to worker progress or completion.

Example

using System;
using System.Threading;
using System.ComponentModel;
 
class Program {
  static BackgroundWorker bw;
  static void Main() {
    bw = new BackgroundWorker();
    bw.WorkerReportsProgress = true;
    bw.WorkerSupportsCancellation = true;
    bw.DoWork += bw_DoWork;
    bw.ProgressChanged += bw_ProgressChanged;
    bw.RunWorkerCompleted += bw_RunWorkerCompleted;
 
    bw.RunWorkerAsync ("Hello to worker");
   
    Console.WriteLine ("Press Enter in the next 5 seconds to cancel");
    Console.ReadLine();
    if (bw.IsBusy) bw.CancelAsync();
    Console.ReadLine();
  }
 
  static void bw_DoWork (object sender, DoWorkEventArgs e) {
    for (int i = 0; i <= 100; i += 20) {
      if (bw.CancellationPending) {
        e.Cancel = true;
        return;
      }
      bw.ReportProgress (i);
      Thread.Sleep (1000);
    }
    e.Result = 123;    // This gets passed to RunWorkerCompleted
  } 
  static void bw_RunWorkerCompleted (object sender,
  RunWorkerCompletedEventArgs e) {
    if (e.Cancelled)
      Console.WriteLine ("You cancelled!");
    else if (e.Error != null)
      Console.WriteLine ("Worker exception: " + e.Error.ToString());
    else
      Console.WriteLine ("Complete - " + e.Result);      // from DoWork
  }
   static void bw_ProgressChanged (object sender,
  ProgressChangedEventArgs e) {
    Console.WriteLine ("Reached " + e.ProgressPercentage + "%");
  }
}
Output

Background worker

Background worker

Advertisements

Responses

  1. Can I use/update public members which are created outside the backgroundworker ?

    Suppose I have:
    public string s;
    public someclass c;

    inside DoWork()

    s = “test”;
    bool result = c.EcecuteSQL(“SELECT ….”);

    thanks


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Categories

%d bloggers like this: