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

I am a software engineer. I have been working with C++, MFC, and .net technologies for 15 Yrs. I like playing video games & 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 | Source

2. ThreadPool Support in C#

C# framework provides ThreadPoolclass 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.

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 | 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 | 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.