Blue Theme Orange Theme Green Theme Red Theme
 
Click Here for 3 Month Free of ASP.NET Hosting!
Home | Forums | Videos | Photos | Downloads | Blogs | E-Books | Interviews | Jobs | Beginners | Training
 | Consulting  
Submit an Article Submit a Blog 
 Login Close
User Id:
Password:
 
Forgot Password
Forgot Username
Why Register
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
 Resources  
Close
 Our Network  
Close
Search :       Advanced Search »
Home » Visual Studio 2010 » Using the BackgroundWorker Component in .NET 2 applications

Using the BackgroundWorker Component in .NET 2 applications

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.

Author Rank:
Technologies: .NET Compact Framework, .NET 1.0/1.1, Controls, Windows Forms,Visual C# .NET
Total downloads :
Total page views :  76616
Rating :
 3.36/5
This article has been rated :  11 times
   Print Read/Post comments Post a comment  Rate  
   Email to a friend  Bookmark  Similar Articles  Author's other articles  
 
Become a Sponsor



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 ! 


Login to add your contents and source code to this article
 [Top] Rate this article
 About the author
 
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 experience working with C, Visual Basic, Oracle, SQL Server, and Access.
Looking for C# Consulting?
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional consulting company, our consultants are well-known experts in .NET and many of them are MVPs, authors, and trainers. We specialize in Microsoft .NET development and utilize Agile Development and Extreme Programming practices to provide fast pace quick turnaround results. Our software development model is a mix of Agile Development, traditional SDLC, and Waterfall models.
Click here to learn more about C# Consulting.
 
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
Go.NET
Build custom interactive diagrams, network, workflow editors, flowcharts, or software design tools. Includes many predefined kinds of nodes, links, and basic shapes. Supports layers, scrolling, zooming, selection, drag-and-drop, clipboard, in-place editing, tooltips, grids, printing, overview window, palette. 100% implemented in C# as a managed .NET Control. Document/View/Tool architecture with many properties&events. Optional automatic layout.
Dundas Software
Dundas Chart for .NET is the most advanced .NET charting package available today.  With an extremely complete feature set, elegant architecture and easy implementation, Dundas Chart can quickly add advanced Charting functionality to enhance and transform ASP.NET and Windows Forms applications.  Whether you are implementing charting into internal projects, or building applications for clients, Dundas Chart offers advanced technology and advanced results to get the most out of data.
Clickatell's SMS Gateway
Clickatell's Developer Solutions allow you to SMS enable any website or application via a range of API's. Learn More about our API connections.
Free access to .NET Memory Management video
Everything you need to know about Garbage Collection, Temporary Objects, Fragmentation, Finalization and common causes of memory leaks in .NET. Watch the video here.
Microsoft Visual Studio 2010
Microsoft Visual Studio 2010 offers more to developers than any other Visual Studio release. Work more productively and collaboratively-with greater control over your work at every step. The Beta 2 can give you a head start on achieving efficiency.
 
   Print Read/Post comments Post a comment  Rate  
   Email to a friend  Bookmark  Similar Articles  Author's other articles  
 
 Post a Feedback, Comment, or Question about this article
Subject:  
Comment:  
Become a Sponsor
 Comments
Not being able to update UI controls by Nacho On February 5, 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?
Reply | Email | Delete | Modify | 
re:Using the BackgroundWorker Component in .NET 2 applications by dimple On March 10, 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
Reply | Email | Delete | Modify | 
Great by priya On July 29, 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.

Reply | Email | Delete | Modify | 

 Hosted by MaximumASP  |  Found a broken link?  |  Contact Us  |  Terms & conditions  |  Privacy Policy  |  Site Map  |  Suggest an Idea  |  Media Kit
Current Version: 5.2009.6.2
 © 1999 - 2009  Mindcracker LLC. All Rights Reserved