Blue Theme Orange Theme Green Theme Red Theme
 
Team Foundation Server Hosting
Home | Forums | Videos | Advertise | Certifications | Downloads | Blogs | Interviews | Jobs | Beginners | Training
 | Consulting  
Submit an Article Submit a Blog 
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
Discover the top 5 tips for understanding .NET Interop
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

Page Views : 44682
Downloads : 1130
Rating :
 Rate it
Level : Advanced
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
Download Files:
BackgroundWorkerDemo.zip
 
 
Nevron Chart
Become a Sponsor
 Tag Cloud
 Latest Jobs
More ... 
 Latest Interview Questions
More ... 


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.

Comment Request!
Thank you for reading this post. Please post your feedback, question, or comments about this post Here.
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.
Discover the Top 5 .NET Memory Management Fundamentals
To write the best .NET code, you need to know exactly how the .NET framework really manages memory. Ricky Leeks presents the Top 5 fundamental facts of .NET memory management. Learn more.
Nevron Chart for .NET 2010.1 Now Available
The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
ASP.NET 4 Hosting
Get 2 Months Free of ASP.NET Hosting for Only $4.95/month! Receive FREE MS SQL and MySQL Databases Including ASP.NET 4/3.5, MVC 3.0, Silverlight 4, Windows 2008/IIS 7.0 Plus FREE IIS 7 Modules. Host UNLIMITED ASP.NET Web Sites – Click Here!
 
 Post a Feedback, Comment, or Question about this article
Subject:
Comment:
Discover the top 5 tips for understanding .NET Interop
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 | Modify 
Using the BackgroundWorker component by Chris On October 11, 2010
Amr, Thanks for taking the time to post this example. It is very helpful indeed!
Reply | Email | Modify 
how to utilise it in the web page by Koteswararao On October 19, 2010
how can i use thin in a web page suppose i click the button and update the lable text on the same page with out refresh page is it possible with the background workerprocess
Reply | Email | Modify 
Discover the top 5 tips for understanding .NET Interop
 © 2012  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.