Background Worker Details & Usage

This is the next article in series of Threading in .Net Applications. This one explains about very simple yet effective tool known as Background Worker. Background worker is basically a component or a tool which can be used in Windows Forms. This tool gives you more control over data or processing intensive applications, it lets you do work in background while keeping the UI responsive.

Using background worker, you can achieve to do multiple things at the same time. Basically it can help u to create a multithreaded application without getting into difficult, time confusing and complicated terms  & details of threading.

This article focus on very basics of Background worker through a sample application. We will move forward through a series of steps as mentioned below:

  1. Open Visual Studio, Create a new project , choosing Windows Forms Application as the template. This form will have a check box which will ask User whether they want to use background worker or not, will have two buttons for “Go” and “Cancel”, a progress bar to report the progress and a Rich text box to show the operation being performed. Additionally it will also have a background worker component. You need to add it in the same way from toolbox as we add other tools on forms. It will not show up on the form but will show up in the grey area at the bottom.  The created form will look like this:formdesign
  2. Add a new class called Person.cs with properties like Name, age & Company.
    //A person with a name, age and company he/she works for
    internal class Person
    {
    // Properties
    public string Name { get; private set; }
    public int Age { get; private set; }
    public string Company { get; private set; }
    //Constructor
    public Person(string name, int age, string company)
    {
    Name = name;
    Age = age;
    Company = company;
    }
    public override string ToString()
    {
    return String.Format("{0} is {1} years old and works for {2}", Name, Age, Company);
    }
    }
  3. Create Events for both the buttons (by switching to properties of Controls and clicking on control for which we want to create event i.e. Go button, Cancel button and background worker) There are basically three events associated with any Background worker which are :
    1. Do Work : This event is used to handle the long running process or data intensive tasks. This event basically runs in the thread other than the UI Thread.
    2. Progress Changed : This event is used to track the progress while do work event is running. basically we can make use of this even to show the user that yes the screen is not freeze but making progress.
    3. Run Worker Completed: This event occurs when Do work is completed and this event can be used to notify the User that task has been completed and next operation can be performed subsequently.
  4. Next up, we need a method where we can have a code which takes up time to execute and gives the feel to user that form has become unresponsive without using background worker. So for that purpose I am using below method
    TimeTakingProcess
  5. Lets move for Go button Click Event. Here first we want to check user wants to use background worker or not, depending on that TimeTakingProcess will be called in separate ways.
    GoClick
    Here you will be noticing a new method called as RunWorkerAsync(). This method is basically starts the Background worker’s Do work Event. Here I am passing the object of Person class as argument to RunWorkerAsync() method. We can call it either without arguments or with arguments.
  6. Now we will consider the Background worker events : DoWork1
    When user opts for using background worker then the same method i.e. TimeTakingProcess() is called inside DoWork Event. Now DoWork is running inside a separate thread i.e. different from UI Thread hence the UI doesn’t becomes unresponsive and user can perform other operations or click on any control on screen. But without using BW, the same method TimeTakingProcess() makes the form unresponsive and in that case user will not be able to click on any control on form.
  7. Here in above code if you see, the progress bar value is updated in the ProgressChanged event through the event arguments which were passed from DoWork event as bwProgress.ReportProgress(i);  One question which must have come in your mind is why I dint updated the progress bar value directly in DoWork Event itself. The reason being Progress bar is created in UI Thread and DoWork runs in a separate thread hence the same cannot be used together as it will lead to cross thread operation. The same line pbProgress.Value = i; if you write in DoWork Event it will throw an InvalidOperationException.
  8. There is a work around if for any situation we want to SET UI control’s values from DoWork Event. This work around involves the use of Invoke method in following way: DoWorkhere the progress bar value and Text box text we are changing from a method which is called via Delegate using Invoke in DoWork Method. Here we will not get the InvalidOperationException reason  being, Invoke executes the delegate on the thread that owns the control’s underlying window handle, with the specified list of arguments. That is delegate is being executed on same thread where the controls are being created hence this doesn’t cause cross thread communication.
  9. Now comes the RunWorkerCompleted event. In this event we can have any code which we want to execute just after the DoWork finishes. In my code I have just written simple code to enable disable buttons.Completed
  10. Lastly the Cancel button Event. This event is used to cancel the DoWork Event of Background worker.CancelEventThis CancelAsync sets the CancellationPending property of background worker to true. if you notice in DoWork Event I am checking if CancellationPending property is true then showing the message Cancelled to User.

In real life applications we can make use of Background worker to do DB related operations or heavy calculations which are more time-consuming than other operations.

That was all from my side for Background worker Usage.

Advertisements

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