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

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
By: Khayralla on June 29, 2009
at 5:56 pm