C# ThreadPool and Its Task Queue Explained (With Example)

Updated on March 13, 2018
sirama profile image

I am a software engineer. I have been working with C++, MFC, and .net technologies for 15 years. I like video games and reading books.

1. Introduction to ThreadPool

A collection of pre-configured Threads sitting alive to serve incoming asynchronous task is called “ThreadPool”. The “System.Threading” namespace contains the ThreadPool class which has many static functions to create and use ThreadPool.

The ThreadPool improves the responsiveness of the application. To explain this, let us think about Yahoo Mail Login Page. Consider, there will be hundreds of users around the world who wants to login in short time period (5-10 Seconds) to check their emails. The Webserver will allocate a thread for each user to check their credentials against the database. But, creating thread, assigning the credential check task and cleaning the thread is time consuming when there are multiple login requests for every second. The web server avoids creating a Thread and cleaning the thread for every request by making use of ThreadPool.

The ThreadPool maintains certain number of threads in the ThreadPool and when there is an incoming task (Like, Login request in the Yahoo Example) assigns that to a Thread in the ThreadPool. When the assigned task is done the Thread will be given back to ThreadPool without destroying it so that it is readily available for next incoming task. This is shown below:

C# Threads and ThreadPool
C# Threads and ThreadPool | Source

2. ThreadPool Support in C#

C# framework provides ThreadPool class to create the Pool of Threads and assign tasks to it. The “QueueUserWorkItem()” method is used to submit the task to the ThreadPool. The “SetMaxThreads()” and “SetMinThreads()” methods are used to control the ThreadPool’s load. In this example we are going to create 50 counting tasks and going to queue them to a ThreadPool.

Setting ThreadPool size requires lot of experiment to maintain the system stability. In this example, we are leaving it to the DotNet CLR.

3. Task for the Threads in ThreadPool

We know that we are going to create ThreadPool and going to queue 50 Tasks to it. What is Task? The task is counting the numbers and printing them in the console output window. Have a look at the below code snippet.

//Sample 02: Define Task/Wait Callback function
private static void TaskCallBack(Object ThreadNumber)
    string ThreadName = "Thread " + ThreadNumber.ToString();
    for (int i =1; i < 10; i++)
        Console.WriteLine(ThreadName + ": " + i.ToString());
    Console.WriteLine(ThreadName + "Finished...");

Here, the TaskCallBack is the function which is nothing but the task that we are going to queue to the ThreadPool. This thread task function receives a parameter to name the Task or Thread. In real world, the parameter is packed with the data required for the Task completion. In our example, we are starting a loop that runs for ten times and prints the counting. Once the counting is done, we are printing that the task assigned for the thread is completed.

Remember, we are going to queue 50 tasks from the main thread and watch how ThreadPool operates on the queued task.

4. Queuing Tasks to ThreadPool

Our Task function is ready. Now in the main() Function, we will queue the tasks one by one. Look at the code snippet below:

Queuing Tasks to C# ThreadPool
Queuing Tasks to C# ThreadPool | Source

We are running a “For Loop” that runs for 50 times. In each iteration, we are queuing a task to the ThreadPool. The QueueUserWorkItem() function (Marked as 1) takes the "WaitCallback Delegate" as parameter. The code snippet Marked as 2 shows that we are passing the task function created in the previous section as parameter for creating the delegate. The second parameter(Marked as 3) passed to the QueueUserWorkItem will be passed as an argument to our "Task Callback Function" by the ThreadPool.

We are passing the Loop counter as second argument and Task function casts that to an integer to form the Thread Name. Note that we are making call to Thread.Sleep(10000) on the main thread. This call will make sure that Main Thread which queued 50 tasks to ThreadPool won’t quit immediately. However, the sleep should be adjusted for system conditions. The best way to wait is through Events which we will see in a separate article.

Now when I run the sample application, I am getting the below sample output (The output varies according to System Conditions):

ThreadPool C# Program Output
ThreadPool C# Program Output | Source

In the output, we can see how the threads executed from the Pool. The above one is just a sample output with a single test run. The output will not be same when we run it next time. Say for example, in our first run we see that Thread 45 finished last. But, in another run you may see different thread stays last.

The complete code example is given below:

C# ThreadPool Complete Code Example

using System;
using System.Collections.Generic;
using System.Text;

//Sample 01: Required Namespace
using System.Threading;

namespace Thread_Pool
    class Program
        //Sample 02: Define Task/Wait Callback function
        private static void 
            TaskCallBack(Object ThreadNumber)
            string ThreadName = "Thread " + 
            for (int i =1; i < 10; i++)
                    + ": " + i.ToString());
                + "Finished...");

        static void Main(string[] args)
            //Sample 03: Create Thread Pool
            for (int task = 1; task < 51; task++)
                    new WaitCallback(TaskCallBack), task);

© 2018 sirama


    0 of 8192 characters used
    Post Comment
    • profile image


      6 weeks ago

      crisp and clear.

      Thank You

    • profile image


      13 months ago

      Great article, short and to the point. Thanks!

    • profile image


      14 months ago

      Good article thank you :-)

    • profile image

      Ammar The Trainer 

      20 months ago

      Nice explanation. Thanks.

    • profile image


      21 months ago

      How to use events instead of Thread.Sleep ?


    This website uses cookies

    As a user in the EEA, your approval is needed on a few things. To provide a better website experience, owlcation.com uses cookies (and other similar technologies) and may collect, process, and share personal data. Please choose which areas of our service you consent to our doing so.

    For more information on managing or withdrawing consents and how we handle data, visit our Privacy Policy at: https://maven.io/company/pages/privacy

    Show Details
    HubPages Device IDThis is used to identify particular browsers or devices when the access the service, and is used for security reasons.
    LoginThis is necessary to sign in to the HubPages Service.
    Google RecaptchaThis is used to prevent bots and spam. (Privacy Policy)
    AkismetThis is used to detect comment spam. (Privacy Policy)
    HubPages Google AnalyticsThis is used to provide data on traffic to our website, all personally identifyable data is anonymized. (Privacy Policy)
    HubPages Traffic PixelThis is used to collect data on traffic to articles and other pages on our site. Unless you are signed in to a HubPages account, all personally identifiable information is anonymized.
    Amazon Web ServicesThis is a cloud services platform that we used to host our service. (Privacy Policy)
    CloudflareThis is a cloud CDN service that we use to efficiently deliver files required for our service to operate such as javascript, cascading style sheets, images, and videos. (Privacy Policy)
    Google Hosted LibrariesJavascript software libraries such as jQuery are loaded at endpoints on the googleapis.com or gstatic.com domains, for performance and efficiency reasons. (Privacy Policy)
    Google Custom SearchThis is feature allows you to search the site. (Privacy Policy)
    Google MapsSome articles have Google Maps embedded in them. (Privacy Policy)
    Google ChartsThis is used to display charts and graphs on articles and the author center. (Privacy Policy)
    Google AdSense Host APIThis service allows you to sign up for or associate a Google AdSense account with HubPages, so that you can earn money from ads on your articles. No data is shared unless you engage with this feature. (Privacy Policy)
    Google YouTubeSome articles have YouTube videos embedded in them. (Privacy Policy)
    VimeoSome articles have Vimeo videos embedded in them. (Privacy Policy)
    PaypalThis is used for a registered author who enrolls in the HubPages Earnings program and requests to be paid via PayPal. No data is shared with Paypal unless you engage with this feature. (Privacy Policy)
    Facebook LoginYou can use this to streamline signing up for, or signing in to your Hubpages account. No data is shared with Facebook unless you engage with this feature. (Privacy Policy)
    MavenThis supports the Maven widget and search functionality. (Privacy Policy)
    Google AdSenseThis is an ad network. (Privacy Policy)
    Google DoubleClickGoogle provides ad serving technology and runs an ad network. (Privacy Policy)
    Index ExchangeThis is an ad network. (Privacy Policy)
    SovrnThis is an ad network. (Privacy Policy)
    Facebook AdsThis is an ad network. (Privacy Policy)
    Amazon Unified Ad MarketplaceThis is an ad network. (Privacy Policy)
    AppNexusThis is an ad network. (Privacy Policy)
    OpenxThis is an ad network. (Privacy Policy)
    Rubicon ProjectThis is an ad network. (Privacy Policy)
    TripleLiftThis is an ad network. (Privacy Policy)
    Say MediaWe partner with Say Media to deliver ad campaigns on our sites. (Privacy Policy)
    Remarketing PixelsWe may use remarketing pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to advertise the HubPages Service to people that have visited our sites.
    Conversion Tracking PixelsWe may use conversion tracking pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to identify when an advertisement has successfully resulted in the desired action, such as signing up for the HubPages Service or publishing an article on the HubPages Service.
    Author Google AnalyticsThis is used to provide traffic data and reports to the authors of articles on the HubPages Service. (Privacy Policy)
    ComscoreComScore is a media measurement and analytics company providing marketing data and analytics to enterprises, media and advertising agencies, and publishers. Non-consent will result in ComScore only processing obfuscated personal data. (Privacy Policy)
    Amazon Tracking PixelSome articles display amazon products as part of the Amazon Affiliate program, this pixel provides traffic statistics for those products (Privacy Policy)
    ClickscoThis is a data management platform studying reader behavior (Privacy Policy)