SIGN UP MEMBER LOGIN:    
ARTICLE

Using the BackgroundWorker Component in .NET 2 Applications

Posted by Michael Livshitz Articles | Articles July 03, 2007
In this article I will show (step-by-step) how you can use the BackgroundWorker Component in .NET 2 applications to execute time-consuming operations.
Reader Level:

The BackgroundWorker Component allows a form to run an operation asynchronously. This is very useful when we deal with such kind of operations as database transactions, image downloads etc. In this case our user interface can hang (or not appear until loading will be finished). In this article I will show (step-by-step) how you can use the BackgroundWorker Component in .NET 2 applications to execute time-consuming operations. The examples are written using C#.

As usually, we create a small test project, named "TestBGW" and having only one form ("FormBGW"):

 

 

Figure 1.

We are going to use the BackgroundWorker Component for some database transaction operation (for example, getting some DataTable). First of all drag and drop onto our form the BackgroundWorker Component:

 

 

Figure 2.

We will use the DataTable to set DataSource property of the DataGridView1. We also should update our user interface and should tell the user, that all our processes are "OK" and he/she should not worry. With this purpose we will use a StatusStrip and a Timer:

 

 

Figure 3.

In order to inform the user that our process is running we will use the toolStripProgressBar1 :

 

 

Figure 4.

To inform the user about status of the process and time, that process has been running, we will use the toolStripStatusLabel1 and the toolStripStatusLabelTime. Our form now looks like this: 

 

 

Figure 5.

In order to simulate database transactions (of course, you can connect to real database; this simulation is only for our test purpose) we use GetData.dll. With this purpose we add reference to GetData.dll and write the getDataTable method:

 

private DataTable getDataTable(int Rows)

{

    GetData.GetDataHelp getData = new GetData.GetDataHelp();

    return (getData.getDataSetCities(Rows).Tables[0]);

}

To start our asynchronous operation we use the RunWorkerAsync method:

 

private void FormBGW_Activated(object sender, EventArgs e)

{

    backgroundWorker1.RunWorkerAsync();

}

The BackgroundWorker Component has three events:

 

 

Figure 6.

The DoWork  event occurs when the RunWokersAsync method is called . Here we "do" our time-consuming work (to do process "time-consuming" we load at least 100000 rows), let the user know that loading is in the progress and set our DataTable as Result of our asynchronous operation:

 

private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)

{

    DataTable dt;

    toolStripStatusLabel1.Text = "Loading ... " + "Thanks for your patience";

    dt = getDataTable(1000000);

    e.Result = dt;

}


In our case (I mean the real situation, when we get some DataTable from some database) we cannot step "into" process and "trace" rows (row-by-row), and, of course, we do not know how many rows we can receive from the database according to our request. Because of that we will not use such method of the DoWorkEventArgs as ReportProgress, which raises the ProgressChanged event. We will use Timer1 to show the user, that our process runs (we will "fill out" the toolStripProgressBar1 up to the maximum and then we will begin from the minimum; that is: we will make some cycle). With this purpose we will add to the timer1_Tick the follow code:

 

if (toolStripProgressBar1.Value == toolStripProgressBar1.Maximum)

{

    toolStripProgressBar1.Value = 0;

}

 

To this method we also will add the code, that allows the user to know how much time the loading is continued. This will be something like that:

 

string sTime ="  ..." + ts.Minutes.ToString("00") +

   ":" + ts.Seconds.ToString("00") +

   ":" + ts.Milliseconds.ToString("000");

toolStripStatusLabelTime.Text = sTime;

 

where ts is "now" time (see the full code below).

By the way, just to try how the ReportProgress works, you can add the follow code to the backgroundWorker1_DoWork method:

 

//-------to try percentage ...

int iMax = 100000;

for (int i = 0; i < iMax; i++)

{

    backgroundWorker1.ReportProgress((i * 100) / (iMax - 1));

}

 

and then the following to the backgroundWorker1_ProgressChanged :

 

private void backgroundWorker1_ProgressChanged(object sender,ProgressChangedEventArgs e)

{

    //-------to try percentage ...

    toolStripProgressBar1.Value = e.ProgressPercentage;

    toolStripStatusLabel1.Text = "Loading ... " +

        e.ProgressPercentage.ToString() + "%";

    //-------------------------

}

The RunWorkerCompleted event occurs when the background operation has completed. Here we will "close" all our messages about loading and bound the dataGridViewCities to the datatable with the help of the RunWorkerComletedEventArgs:

 

dataGridViewCities.DataSource = e.Result;

The full code of the FormBGW.cs is the following: 

 

using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Text;

using System.Windows.Forms;

 

namespace TestBGW

{

    public partial class FormBGW : Form

    {

        public FormBGW()

        {

            InitializeComponent();

            ////to try percentage ...

            //backgroundWorker1.WorkerReportsProgress = true;

        }

        #region "forClass"

        DateTime startDate = DateTime.Now;

        #endregion

 

        private void FormBGW_Activated(object sender, EventArgs e)

        {

            backgroundWorker1.RunWorkerAsync();

            timer1.Start();

        }

        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)

        {

            DataTable dt;

            toolStripStatusLabel1.Text = "Loading ... " +

                "Thanks for your patience";

            dt = getDataTable(1000000);

            ////-------to try percentage ...

            //int iMax = 100000;

            //for (int i = 0; i < iMax; i++)

            //{

            //    backgroundWorker1.ReportProgress

            //        ((i * 100) / (iMax - 1));

            //}

            ////-------------------------

            e.Result = dt;

            toolStripStatusLabel1.Text = "Please, wait ...";

        }

 

        private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)

        {

            ////-------to try percentage ...

            //toolStripProgressBar1.Value = e.ProgressPercentage;

            //toolStripStatusLabel1.Text = "Loading ... " +

            //    e.ProgressPercentage.ToString() + "%";

            ////-------------------------

        }

 

        private void backgroundWorker1_RunWorkerCompleted(object sender,RunWorkerCompletedEventArgs e)

        {

            toolStripProgressBar1.Value = 100;

            dataGridViewCities.DataSource = e.Result;

            toolStripStatusLabel1.Text = "";

            toolStripProgressBar1.Value = 0;

            timer1.Stop();

            toolStripStatusLabelTime.Text = "";

        }

 

        private DataTable getDataTable(int Rows)

        {

            GetData.GetDataHelp getData = new GetData.GetDataHelp();

            return (getData.getDataSetCities(Rows).Tables[0]);

        }

 

        private void timer1_Tick(object sender, EventArgs e)

        {

            TimeSpan ts = DateTime.Now.Subtract(startDate);

            string sTime ="  ..." + ts.Minutes.ToString("00") +

               ":" + ts.Seconds.ToString("00") +

               ":" + ts.Milliseconds.ToString("000");

            toolStripStatusLabelTime.Text = sTime;

            if (toolStripProgressBar1.Value ==

                toolStripProgressBar1.Maximum)

            {

                toolStripProgressBar1.Value = 0;

            }

            toolStripProgressBar1.PerformStep();

        }

    }

}


Now, if we start our project, we will see :

 

Figure 7.

 

And after loading:

 



Figure 8.

CONCLUSION

I hope that this article will help you to use the BackgroundWorker Component  in your .NET 2 applications to execute time-consuming operations.


Good luck in programming ! 

share this article :
post comment
 

It's realy good.I clear my doubt as well as I learn something from you.

Thank you so much

Posted by Tanmay Sarkar Jul 02, 2010

A cross thread error will raise at the line "Loading...Thanks for your patience", please check this program and suggest a solution.I appreciate your work.

Thanks
Baskar

Posted by mdbaskaran Dec 11, 2009

Hey, this is a great article.It resolved most of my doubts related to Background worker esp related to the progress bar value when we query to the database.

Posted by priya paluru Jul 29, 2009

Nice one..really helpful Thanks!! but i got error when i debug on the event backgroundWorker1_DoWork. "backgroundWorker1 is busy in another operation like" Thanks Vineetha

Posted by Vineetha Mathew Mar 10, 2009

The line: toolStripStatusLabel1.Text = "Loading ... " +"Thanks for your patience"; returns an error to me : "Cross-thread operation not valid: Control 'label1' accessed from a thread other than the thread it was created on" I understand that I cannot change controls in the interface, only members of the worker thread. Are you sure this code is working?

Posted by Nacho George Feb 05, 2009
Nevron Gauge for SharePoint
Become a Sponsor
PREMIUM SPONSORS
  • Get 2 Months Free of ASP.NET Hosting for Only $4.95/month! Receive FREE MS SQL and MySQL Databases Including ASP.NET 4/3.5, MVC 3.0, Silverlight 4, Windows 2008/IIS 7.0 Plus FREE IIS 7 Modules. Host UNLIMITED ASP.NET Web Sites - Click Here!
    The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
6 Months Free & No Setup Fees ASP.NET Hosting!
Become a Sponsor