Blue Theme Orange Theme Green Theme Red Theme
 
MindFusion's Components
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 .NET » Using the BackgroundWorker component

Using the BackgroundWorker component

This article discusses the BackgroundWorker component in .NET 2.0, it will show you how to use it to execute tasks in the background of your application

Technologies: .NET 1.0/1.1,Visual C# .NET
Total downloads : 647
Total page views :  22658
Rating :
 4.63/5
This article has been rated :  8 times
   Print Read/Post comments Post a comment  Rate  
   Email to a friend  Bookmark  Similar Articles  Author's other articles  
Download Files:
BackgroundWorkerDemo.zip
 
Become a Sponsor


Related EbooksTop Videos


Introduction:

The BackgroundWorker allows you to execute operations that take a long period of time such as database transaction or file downloads, asynchronously on a separate thread and allow the user interface to remain responsive.

Start an Operation in the Background:

First, you need to add an instance of the BackgroundWorker component to you application, if you use visual studio, just drag it from the toolbox to your application or you can create it manually as follow:

BackgroundWorker backgroundWorker1 = new BackgroundWorker();

To start the operation in the background you have to call the RunWorkerAsync() method of the BackgroundWorker, when you call this method the BackgroundWroker starts the execution of the background operation by raising the DoWork event, the code in the DoWork event handler is executed on a separate thread.

Example:

BackgroundWorker backgroundWorker1 = new BackgroundWorker();

//start the operation on another thread

private void btnStart_Click(object sender, EventArgs e)

{

    backgroundWorker1.RunWokerAsync();

}

//DoWork event handler is executed on a separate thread

private void backgroundWorker1_DoWork(object sender, DoWorkeventArgs e)

{

    //a long running operation

    Thread.Sleep(5000);
}

You can send a parameter to the background operation using the RunWorkerAsync() method. You can recieve this parameter by using the Argument property of the instance of DoWorkEventArgs in the DoWork event handler then you cast it to use it in the background operation.

Example:

BackgroundWorker backgroundWorker1 = new BackgroundWorker();

//start the operation on another thread

private void btnStart_Click(object sender, EventArgs e)

{

    backgroundWorker1.RunWokerAsync(2000);

}

//DoWork event handler is executed on a separate thread

private void backgroundWorker1_DoWork(object sender, DoWorkeventArgs e)

{

    int input = (int)e.Argument;

    //a long running operation

    Thread.Sleep(input);

}

Reporting progress of a background operation using BackgroundWorker:

By using the BackgroundWorker you have the ability to report progress updates of the executing operation. To use this options you must set the WorkerReportsProgress to true.

To start report progress you call ReportProgress() method and use it to pass a parameter that have the value of the percentage of the progress that have been completed. This method raises the BackgroundWorker.ProgressChanged event. In the event handler of the ProgressChanged you can recieve the value of the progress precentage on the main thread using the ProgressPercentage property of the instance of ProgressChangedEventArgs.

Example:

BackgroundWorker backgroundWorker1 = new BackgroundWorker();

backgroundWorker1.WorkerReportsProgress = true;

//start the operation on another thread

private void btnStart_Click(object sender, EventArgs e)

{

    backgroundWorker1.RunWokerAsync();

}

//DoWork event handler is executed on a separate thread

private void backgroundWorker1_DoWork(object sender, DoWorkeventArgs e)

{

    //a long running operation

    for (int i = 1; i < 11; i++)

    {   

        Thread.Sleep(2000);

        backgroundWorker1.ReportProgress(i*10);

    }

}

private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)

{

    progressBar1.value = e.ProgressPercentage;

}

Cancelling a background operation using BackgroundWorker:

With the BackgroundWorker you have the ability to cancel the background operation, to do this you first must set WorkerSupportsCancellation property to true.

The next step is to call the CancelAsync() method by doing so you sets the CancellationPending property to true, by polling the CancellationPending property you can determine whether or not to cancel the background operation.

Example:

BackgroundWorker backgroundWorker1 = new BackgroundWorker();

backgroundWorker1.WorkerSupportsCancellation = true;

//start the operation on another thread

private void btnStart_Click(object sender, EventArgs e)

{

    backgroundWorker1.RunWokerAsync();

}

//a buttun to cancel the operation

private void btnCancel_Click(object sender, EventArgs e)

{

    backgroundWorker1.CancelAsync();

}

//DoWork event handler is executed on a separate thread

private void backgroundWorker1_DoWork(object sender, DoWorkeventArgs e)

{

    //a long running operation

    for (int i = 1; i < 11; i++)

    {

        Thread.Sleep(2000);

        backgroundWorker1.ReportProgress(i*10);

 

        if(backgroundWorker1.CancellationPending)

        {

            e.cancel = true;

            return;

        }

    }

}

Alert the user in the completion of the background operation:

When the background operation completes, whether because the backgroud operation is completed or cancelled, the RunWorkerCompleted event is raised. You can alert the user to the completion by handling the RunWorkerCompleted event.

You can determine if the user cancelled the operation by using the Cancelled property of the instance RunWorkerCompletedEventArgs.

Example:

BackgroundWorker backgroundWorker1 = new BackgroundWorker();

//start the operation on another thread

private void btnStart_Click(object sender, EventArgs e)

{

    backgroundWorker1.RunWokerAsync();

}

//a buttun to cancel the operation

private void btnCancel_Click(object sender, EventArgs e)

{

    backgroundWorker1.CancelAsync();

} 

//DoWork event handler is executed on a separate thread

private void backgroundWorker1_DoWork(object sender, DoWorkeventArgs e)

{

    //a long running operation

    for (int i = 1; i < 11; i++)

    {

        Thread.Sleep(2000);

        backgroundWorker1.ReportProgress(i*10);

 

        if (backgroundWorker1.CancellationPending)

        {

            e.Cancel = true;

            return;

        }

    }

} 

private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)

{

    if(e.Cancelled)

    {

        MessageBox.Show("Operation Cancelled");

    }

    else

    {

        MessageBox.Show("OperationCompleted");

    }

}


 

Return a value from the background operation:

You can return a value from the background operation that in the DoWork event handler using the Result property of the DoWorkEventArgs instance, and you can recieve it in the RunWorkerCompleted event handler using the Result property of the RunWorkerCompletedEventArgs instance.

Example:

BackgroundWorker backgroundWorker1 = new BackgroundWorker();

//start the operation on another thread

private void btnStart_Click(object sender, EventArgs e)

{

    backgroundWorker1.RunWokerAsync();

}

//DoWork event handler is executed on a separate thread

private void backgroundWorker1_DoWork(object sender, DoWorkeventArgs e)

{

    //a long running operation here

    Thread.Sleep(2000);

    //return the value here

    e.Result = 10;

}

private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)

{

    //recieve the return value here

    int returnValue = (int)e.Result;

}

 

you can see the full code of these examples after downloading the files with this article.


Login to add your contents and source code to this article
 [Top] Rate this article
 About the author
 
Amr Monjid
Amr Monjid is a computer programmer from Egypt. He has experience with C#, .Net framework, ASP.NET, Windows Applications, ADO.NET, Xml, Web Services, Custom Controls, and e-commerce web sites. and he is a MCTS: .NET framework 2.0, Windows Application, Distributed Aplication.
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  
Download Files:
BackgroundWorkerDemo.zip
 
 Post a Feedback, Comment, or Question about this article
Subject:  
Comment:  
Powerful ASP.NET Hosting w/ NO Setup Fees. Click Here!
Become a Sponsor
 Comments
thanks brother by Mohamed On June 17, 2009
good example
can u give me an example how to use ur example to retrieve records from database and populate a datagridview

thanks in advance
Mohamad Abdullah
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