Reader Level:
Articles

Using the BackgroundWorker Component in .NET 2 Applications

By Michael Livshitz on 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.
  • 0
  • 0
  • 156860

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 usual, we create a small test project, named "TestBGW" and having only one form ("FormBGW"):

 

1.jpg

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:

 

2.jpg

Figure 2.

We will use the DataTable to set the 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:

 

3.jpg

Figure 3.

To inform the user that our process is running we will use the toolStripProgressBar1:

 

4.jpg

Figure 4.

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

 

5.jpg

Figure 5.

To simulate database transactions (of course, you can connect to a real database; this simulation is only for our test purpose) we use GetData.dll. For that purpose we add a 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:

 

6.jpg

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 the 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" a 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 a 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 following 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 has taken. This will be something like:

 

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 bind 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:

7.jpg

Figure 7.

 

And after loading:

 

8.jpg

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 ! 

Michael Livshitz

Michael is a lead programmer for a large technological firm. He has experience working with .NET projects (ASP.NET and Windows) since 2002. Currently used languages are C#, VB.NET, T-SQL and JavaScript. He also has exper... Read more

COMMENT USING

Trending up