Click here to Skip to main content
Click here to Skip to main content

Tagged as

Go to top

Thread Pooling in C# – BackgroundWorker

, 18 Feb 2014
Rate this:
Please Sign up or sign in to vote.
The BackgroundWorker class allows you to run an operation on a separate, dedicated thread. Time-consuming operations, such as calling third party API/service, downloads and database transactions, can cause your user interface to stop responding. You should use BackgroundWorkder when you want a respo

The BackgroundWorker class allows you to run an operation on a separate, dedicated thread. Time-consuming operations, such as calling third party API/service, downloads and database transactions, can cause your user interface to stop responding. You should use BackgroundWorkder when you want a responsive user interface and you must perform time-consuming operations.

using System;
using System.ComponentModel;
using System.Threading;

namespace TestConsole
{
    class Program
    {
        public static void Main(string[] args)
        {
           var backgroundWorker = new BackgroundWorker
                                      {
                                          WorkerReportsProgress = true,
                                          WorkerSupportsCancellation = true
                                      };
            backgroundWorker.DoWork += new DoWorkEventHandler(DoLongWork);
            backgroundWorker.ProgressChanged += new ProgressChangedEventHandler(
                ProgressChanged);
            backgroundWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(
                OperationCompleted);
            backgroundWorker.RunWorkerAsync();  //Start worker thread

            //You can comment/uncomment below two lines and see what happens
            Thread.Sleep(3000);
            //Cancel worker thread even if it has not completed
            backgroundWorker.CancelAsync();   

            Console.WriteLine("Main thread ends");
            Console.ReadKey();
        }

        public static void DoLongWork(object sender, DoWorkEventArgs e)
        {
            var worker = sender as BackgroundWorker;
            Console.WriteLine("Operation has started");
            for (var i = 1; i <= 5; i++)
            {
                //Cancel operation in between if requested
                if ((worker.CancellationPending == true)) 
                {
                    Console.WriteLine("Operation has been cancelled in between");
                    e.Cancel = true;
                    break;
                }
                // Perform a time consuming operation and report progress.
                Thread.Sleep(1000);
                //Report current progress so that it can be updated on UI
                worker.ReportProgress((i * 20));  
            }
            Console.WriteLine("End of DoLongWork method");
        }

        public static void ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            //Update progress on UI
            Console.WriteLine("Operation has completed {0}%", e.ProgressPercentage);
        }

        public static void OperationCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            Console.WriteLine(
                "Operation has either completed successfully or has been cancelled");
        }

    }
}

I have provided rich comments in the program so that it would be easy for you to understand how BackgroundWorker works. You can also learn more about BackgroundWorker by commenting/uncommenting some lines and see their impact. For eg: If you could comment line which sets WorkerReportProgress = true; and see if progress is reported i.e. updateProgress method is called or not.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Adarsh Chaurasia (Consultant|Mentor|Tech Savvy)
Software Developer (Senior)
India India
I have 4.6+ years of experience in SaaS, SOA based Enterprise Web Application design and development using Microsoft technology stack. I have mostly worked on Business layer, Data access layer, WCF, Entity Framework, Microsoft Application Blocks, Search engines, APIs integration, Third party APIs/Product Research & Development.
 
I am a huge fan of Design Patterns. I also work as Software Consultant. I read/write blogs, help and learn from other developers.
Follow on   Twitter   LinkedIn

Comments and Discussions

 
GeneralMy vote of 2 PinmemberTylerD8719-Feb-14 4:21 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web02 | 2.8.140921.1 | Last Updated 18 Feb 2014
Article Copyright 2014 by Adarsh Chaurasia (Consultant|Mentor|Tech Savvy)
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid