As usual, 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 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:

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

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:

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]);
- }
- private void FormBGW_Activated(object sender, EventArgs e)
- {
- backgroundWorker1.RunWorkerAsync();
- }

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;
- }
- if (toolStripProgressBar1.Value == toolStripProgressBar1.Maximum)
- {
- toolStripProgressBar1.Value = 0;
- }
- string sTime =" ..." + ts.Minutes.ToString("00") +
- ":" + ts.Seconds.ToString("00") +
- ":" + ts.Milliseconds.ToString("000");
- toolStripStatusLabelTime.Text = sTime;
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));
- }
- private void backgroundWorker1_ProgressChanged(object sender,ProgressChangedEventArgs e)
- {
- //-------to try percentage ...
- toolStripProgressBar1.Value = e.ProgressPercentage;
- toolStripStatusLabel1.Text = "Loading ... " +
- e.ProgressPercentage.ToString() + "%";
- //-------------------------
- }
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();
- }
- }
- }

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!
Tanmay SarkarPosted Jul 2, 2010, 11:27 AM
It's realy good.I clear my doubt as well as I learn something from you. Thank you so much
mdbaskaranPosted Dec 11, 2009, 11:52 AM
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
priya paluruPosted Jul 29, 2009, 10:40 AM
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.
Vineetha MathewPosted Mar 10, 2009, 10:00 AM
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
Nacho GeorgePosted Feb 5, 2009, 5:05 AM
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?