.NET: Updated: Simple and Stupid BackgroundWorker Example

I was very busy the past weeks, I cannot imagine I could make it not to code for several days, been a carpenter, janitor, messenger and everything hehe. But I'm here again now. Let me start this out with this stupid sample I just given to one of my junior developer.

BackgroundWorker is a special class in .NET 2.0 to help developers implement non-freezing UI, multi-threaded windows forms applications. It provides intuitive model for hanldling events, reporting progress, and notifying the user interface. 

In my opinion, it is a must for all windows forms developers to know this and learn how to implement this. But the problem I can see is that, most of times junior developers dont know where to start and sometimes overwelemed by the documentations most websites and microsft provided. Lets keep it this simple :).

Instructions:

  1. Create a new VS2005 C# Window Forms project.
  2. Add a new Form, name it "WinAppMain".
  3. On form add two buttons "btnStart" and "btnStop".
  4. Add a label "lblStatus".
  5. Add a progressbar control "progressBar".

Then review and implement this code, sorry but you cannot copy this hehe.

    2   Description: very simple background worker sample

  

    6 using System;

    7 using System.Collections.Generic;

    8 using System.ComponentModel;

    9 using System.Threading;

   10 using System.Windows.Forms;

   11 

   12 namespace WindowAppEx {

   13     public partial class WinAppMain : Form {

   14         //class level variables

   15         List<string> employees = new List<string>();

   16         private BackgroundWorker worker = null;

   17 

   18         public WinAppMain() {

   19             InitializeComponent();

   20         }

   21 

   22         private void btnStart_Click(object sender, EventArgs e) {

   23             btnStart.Enabled = false;

   24             btnStop.Enabled = true;

   25 

   26             InitializeList();

   27             InitializeBar();

   28             RunWorker();

   29         }

   30 

   31         //initilaize progress nar

   32         private void InitializeBar() {

   33             progressBar.Maximum = 100;

   34             progressBar.Minimum = 0;

   35             progressBar.Value = 0;

   36         }

   37 

   38         //create a dummy list, assume this is a list of employees to be processed on a backgroun thread

   39         private void InitializeList() {

   40             employees.Add("Marilyn Manalo");

   41             employees.Add("Shereen Guinucud");

   42             employees.Add("Eunice Hosmillo");

   43             employees.Add("Haizel Lin");

   44             employees.Add("Rizchelle Priagula");

   45             employees.Add("Cyd Clarence Petalino");

   46             employees.Add("June Aileen Fesariton");

   47             employees.Add("Gwendale Gertrude Aranas ");

   48             employees.Add("Juvy ViƱas");

   49         }

   50 

   51         //create a new backround worker

   52         private void RunWorker() {

   53             worker = new BackgroundWorker();

   54             worker.WorkerReportsProgress = true;

   55             worker.WorkerSupportsCancellation = true;

   56 

   57             worker.DoWork += new DoWorkEventHandler(worker_DoWork);

   58             worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(worker_RunWorkerCompleted);

   59             worker.ProgressChanged += new ProgressChangedEventHandler(worker_ProgressChanged);

   60             worker.RunWorkerAsync(employees);

   61         }

   62 

   63         //begin working on files

   64         private void worker_DoWork(object sender, DoWorkEventArgs e) {

   65             BackgroundWorker senderWorker = sender as BackgroundWorker;

   66             List<string> inputList = e.Argument as List<string>;

   67 

   68             for (int index = 0; index<= inputList.Count-1; index++) {

   69                 //do more work here

   70                 Thread.Sleep(1000);

   71 

   72                 int   progressInPercent = (int)(((decimal)(index + 1)/(decimal)inputList.Count) * 100);

   73                 worker.ReportProgress(progressInPercent, inputList[index]);

   74 

   75                 //handle cancellation of the thread, even CancelAsync was called, the worker is still processing request

   76                 //explict hanlding of cancellation is needed here to avoud null reference exception

   77                 if(senderWorker.CancellationPending) {

   78                     e.Cancel = true;

   79                     break;

   80                 }

   81             }

   82         }

   83 

   84         //executed when worker was finished

   85         private void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) {

   86             lblStatus.Text = "work finished processing request.";

   87         }

   88 

   89         //executed when worker finished processign one item

   90         private void worker_ProgressChanged(object sender, ProgressChangedEventArgs e) {

   91             progressBar.Value = e.ProgressPercentage;

   92             lblStatus.Text = "working on file of: " + e.UserState;

   93         }

   94 

   95         //worker cancelled when cancel button was clicked

   96         private void btnStop_Click(object sender, EventArgs e) {

   97             worker.CancelAsync();

   98             lblStatus.Text = "work was stopped.";

   99 

  100             btnStart.Enabled = true;

  101             btnStop.Enabled = false;

  102         }

  103     }

  104 }

 

 

 


 

You can also create multiple background workers running at the same time. HTH.

Comments

# Dennis said:

Anong kayang mangyayari pag twice kong i click 'yong btnStart.  :)   thanks.

Wednesday, June 20, 2007 1:46 PM
# jokiz said:

good question dennis

Wednesday, June 20, 2007 7:31 PM
# cruizer said:

dapat siguro eh idisable yun start button pag napindot na para wag mapindot ulit? :)

Wednesday, June 20, 2007 9:02 PM
# dehran ph said:

nice catch dennis, i fixed it already also an exception raised when worker was cancelled.

Wednesday, June 20, 2007 10:24 PM
# jokiz said:

so here's another question, what if in a webform/asp.net page, you clicked on a process button page twice? does the processing of the initial request stop when the second request start?

Thursday, June 21, 2007 2:32 AM
# Joseph said:

At the top of my head, I think the initial request wil continue, the second request will be handled separately.

Monday, June 25, 2007 10:02 PM
# Buspar and weight gain. said:

Buspar side effects. Buspar anxiety. Buspar. Buspar buy online cheap.

Monday, November 17, 2008 4:54 PM

Leave a Comment

(required) 
(required) 
(optional)
(required) 

Enter the numbers above: