Thursday, 5 December 2013

Background worker in .Net

We might want to run two or more independent tasks simultaneously rather than running them synchronously. If you talk about asynchronous programming threads concept is the first one to come in our mind. Well its true but Microsoft has given us extra bit of abstraction through background worker. Background worker runs on a different thread and performs tasks asynchronously.

We will show you coding part now.
1. Add reference to System.ComponentModel name space in order to access background worker class.

using System.ComponentModel;

2. Now declare a variable of type Background worker and instantiate it in page_load event of the page as shown below. In addition to that register two events of background worker namely DoWork and RunWorkerCompleted. We will discuss them later in this post.

protected void Page_Load(object sender, EventArgs e)
{
            bWorker = new BackgroundWorker();
            bWorker.DoWork += new DoWorkEventHandler(bWorker_DoWork);
            bWorker.RunWorkerCompleted += new           RunWorkerCompletedEventHandler(bWorker_RunWorkerCompleted);
}

protected void bWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
         
}

protected void bWorker_DoWork(object sender, DoWorkEventArgs e)
{
         
}


3. Now we will write two simple methods namely Task1() and Task2(). We will execute these two methods asynchronously using background worker in later steps.

void Task1()
{
            // Load data from Source1
 }
void Task2()
{
            // Load data from Source2
}

4. Now we want these two methods to be called in page_load. Hence we would change our page_load event as shown below.

protected void Page_Load(object sender, EventArgs e)
{
            bWorker = new BackgroundWorker();
            bWorker.DoWork += new DoWorkEventHandler(bWorker_DoWork);
            bWorker.RunWorkerCompleted += new      RunWorkerCompletedEventHandler(bWorker_RunWorkerCompleted);
            Task1();
            bWorker.RunWorkerAsync();
}

5. Please notice the above code carefully. We made two changes one is we are directly calling Task1(), the second one is we are calling RunWorkerAsync() method of background worker. This RunWorkerAsync() will raise DoWork event of the background worker where we have to call Task2().

protected void bWorker_DoWork(object sender, DoWorkEventArgs e)
{
            Task2();
}

6. We are almost done. You might be having questions regarding RunWorkerCompleted event of the background worker. It is useful to perform operations once after background worker completes processing. For instance hiding the loading popup dialog or some other operations.

7. To sum up everything:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.ComponentModel;

namespace BlogPosts
{
    public partial class _Default : System.Web.UI.Page
    {

        BackgroundWorker bWorker;

        protected void Page_Load(object sender, EventArgs e)
        {
            bWorker = new BackgroundWorker();
            bWorker.DoWork += new DoWorkEventHandler(bWorker_DoWork);
            bWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bWorker_RunWorkerCompleted);
            Task1();
            bWorker.RunWorkerAsync();
        }

        protected void bWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
         
        }

        protected void bWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            Task2();
        }

       void Task1()
       {
            // Load data from Source1
        }
       void Task2()
      {
            // Load data from Source2
       }
    }
}

Thigs to Remember: You can not access UI controls such as labels textboxes etc in DoWork event. For example if you try to set Text property of a label from DoWork event an exception will be thrown because label belongs to UI thread not the background worker's thread. Hence Hence those operations should be performed in  RunWorkerCompleted Event of the background worker.

, , , , ,

No comments:

Post a Comment