Click here to Skip to main content
12,550,111 members (47,623 online)
Click here to Skip to main content
Add your own
alternative version

Tagged as


7 bookmarked

Thread Pooling in C# – BackgroundWorker

, 18 Feb 2014 CPOL
Rate this:
Please Sign up or sign in to vote.
Thread pooling in C# - BackgroundWorker

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(
            backgroundWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(
            backgroundWorker.RunWorkerAsync();  //Start worker thread

            //You can comment/uncomment below two lines and see what happens
            //Cancel worker thread even if it has not completed

            Console.WriteLine("Main thread ends");

        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;
                // Perform a time consuming operation and report progress.
                //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)
                "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 example: If you could comment line which sets WorkerReportProgress = true; and see if progress is reported, i.e., updateProgress method is called or not.


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


About the Author

Adarsh Chaurasia - Enjoying Full Stack Development
Software Developer (Senior)
India India
 Innovative & tech-savvy software development professional with 6+ years of progressive experience specializing in object-oriented approach to enterprise commercial solution delivery utilizing latest technologies.
 Extensive background in Full Life-Cycle of Software Development and Automation process including requirements gathering, design, coding, unit testing, automation, debugging and maintenance.
 Comprehensive knowledge of Relational Database technology, queries and procedures.
 Excellent understanding of OOPS Concepts, Design Patterns & Best Coding Practices.
 Strong architectural knowledge of designing n-tier and n-layer solutions using Application blocks, Enterprise library, SOA, Software factories.
 Working experience of IIS administration and website deployment and configuration.

Strengths & Area of expertise include:

 Full Stack Enterprise Web Development
 Multi-Threaded Programming
 Object Oriented Development
 REST APIs Development & Integration
 Distributed/Client Server System
 TDD & Behavior Driven Development (BDD)
 Database Design & Development
 Exceptional Analytical & Quick Learning Skill
 Team & Client Communication
 Proactive & Organization Development Attitude

You may also be interested in...


Comments and Discussions

GeneralMy vote of 2 Pin
TylerD8719-Feb-14 4:21
memberTylerD8719-Feb-14 4:21 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    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 | Terms of Use | Mobile
Web01 | 2.8.161021.1 | Last Updated 18 Feb 2014
Article Copyright 2014 by Adarsh Chaurasia - Enjoying Full Stack Development
Everything else Copyright © CodeProject, 1999-2016
Layout: fixed | fluid