Using the BackgroundWorker Component in .NET 2 Applications

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:

  1. private DataTable getDataTable(int Rows)  
  2. {  
  3.     GetData.GetDataHelp getData = new GetData.GetDataHelp();  
  4.     return (getData.getDataSetCities(Rows).Tables[0]);  
  5. }  
To start our asynchronous operation we use the RunWorkerAsync method:
  1. private void FormBGW_Activated(object sender, EventArgs e)  
  2. {  
  3.     backgroundWorker1.RunWorkerAsync();  
  4. }  
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: 

  1. private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)  
  2. {  
  3.     DataTable dt;  
  4.     toolStripStatusLabel1.Text = "Loading ... " + "Thanks for your patience";  
  5.     dt = getDataTable(1000000);  
  6.     e.Result = dt;  
  7. }  
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:
  1. if (toolStripProgressBar1.Value == toolStripProgressBar1.Maximum)  
  2. {  
  3.     toolStripProgressBar1.Value = 0;  
  4. }  
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: 
  1. string sTime ="  ..." + ts.Minutes.ToString("00") +  
  2.    ":" + ts.Seconds.ToString("00") +  
  3.    ":" + ts.Milliseconds.ToString("000");  
  4. 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: 

  1. //-------to try percentage ...  
  2. int iMax = 100000;  
  3. for (int i = 0; i < iMax; i++)  
  4. {  
  5.     backgroundWorker1.ReportProgress((i * 100) / (iMax - 1));  
  6. }  
and then the following to the backgroundWorker1_ProgressChanged :
  1. private void backgroundWorker1_ProgressChanged(object sender,ProgressChangedEventArgs e)  
  2. {  
  3.     //-------to try percentage ...  
  4.     toolStripProgressBar1.Value = e.ProgressPercentage;  
  5.     toolStripStatusLabel1.Text = "Loading ... " +  
  6.     e.ProgressPercentage.ToString() + "%";  
  7.     //-------------------------  
  8. }
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:

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.ComponentModel;  
  4. using System.Data;  
  5. using System.Drawing;  
  6. using System.Text;  
  7. using System.Windows.Forms;  
  8.   
  9. namespace TestBGW  
  10. {  
  11.     public partial class FormBGW : Form  
  12.     {  
  13.         public FormBGW()  
  14.         {  
  15.             InitializeComponent();  
  16.             ////to try percentage ...  
  17.             //backgroundWorker1.WorkerReportsProgress = true;  
  18.         }  
  19.         #region "forClass"  
  20.         DateTime startDate = DateTime.Now;  
  21.         #endregion  
  22.         private void FormBGW_Activated(object sender, EventArgs e)  
  23.         {  
  24.             backgroundWorker1.RunWorkerAsync();  
  25.             timer1.Start();  
  26.         }  
  27.         private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)  
  28.         {  
  29.             DataTable dt;  
  30.             toolStripStatusLabel1.Text = "Loading ... " +  
  31.                 "Thanks for your patience";  
  32.             dt = getDataTable(1000000);  
  33.             ////-------to try percentage ...  
  34.             //int iMax = 100000;  
  35.             //for (int i = 0; i < iMax; i++)  
  36.             //{  
  37.             //    backgroundWorker1.ReportProgress  
  38.             //        ((i * 100) / (iMax - 1));  
  39.             //}  
  40.             ////-------------------------  
  41.             e.Result = dt;  
  42.             toolStripStatusLabel1.Text = "Please, wait ...";  
  43.         }  
  44.         private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)  
  45.         {  
  46.             ////-------to try percentage ...  
  47.             //toolStripProgressBar1.Value = e.ProgressPercentage;  
  48.             //toolStripStatusLabel1.Text = "Loading ... " +  
  49.             //    e.ProgressPercentage.ToString() + "%";  
  50.             ////-------------------------  
  51.         }  
  52.         private void backgroundWorker1_RunWorkerCompleted(object sender,RunWorkerCompletedEventArgs e)  
  53.         {  
  54.             toolStripProgressBar1.Value = 100;  
  55.             dataGridViewCities.DataSource = e.Result;  
  56.             toolStripStatusLabel1.Text = "";  
  57.             toolStripProgressBar1.Value = 0;  
  58.             timer1.Stop();  
  59.             toolStripStatusLabelTime.Text = "";  
  60.         }  
  61.         private DataTable getDataTable(int Rows)  
  62.         {  
  63.             GetData.GetDataHelp getData = new GetData.GetDataHelp();  
  64.             return (getData.getDataSetCities(Rows).Tables[0]);  
  65.         }  
  66.         private void timer1_Tick(object sender, EventArgs e)  
  67.         {  
  68.             TimeSpan ts = DateTime.Now.Subtract(startDate);  
  69.             string sTime ="  ..." + ts.Minutes.ToString("00") +  
  70.                ":" + ts.Seconds.ToString("00") +  
  71.                ":" + ts.Milliseconds.ToString("000");  
  72.             toolStripStatusLabelTime.Text = sTime;  
  73.             if (toolStripProgressBar1.Value ==  
  74.                 toolStripProgressBar1.Maximum)  
  75.             {  
  76.                 toolStripProgressBar1.Value = 0;  
  77.             }  
  78.             toolStripProgressBar1.PerformStep();  
  79.         }  
  80.     }  
  81. }  
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!


Similar Articles