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 tasks is called “ThreadPool.” The “System.Threadin” 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 that hundreds of users worldwide that want to log in in a short time (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 a thread, assigning the credential check task, and cleaning the thread is time-consuming when multiple login requests occur every second. The web server avoids creating a thread and cleaning the thread for every request by making use of ThreadPool.
The ThreadPool maintains a certain number of threads in the ThreadPool, and when there is an incoming task (like a login request in the Yahoo example), it 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 the next incoming task. This is shown below:
2. ThreadPool Support in C#
C# framework provides ThreadPool a 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 will create 50 counting tasks and queue them to a ThreadPool.
Setting ThreadPool size requires a lot of experiments to maintain 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 that is nothing but the task we will queue to the ThreadPool. This thread task function receives a parameter to name the task or thread. In the real world, the parameter is packed with the data required for task completion. In our example, we are starting a loop that runs 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:
We are running a "for loop" that runs 50 times. In each iteration, we are queuing a task to the ThreadPool. The QueueUserWorkItem() function (marked as 1) takes the "WaitCallback Delegate" as a parameter. The code snippet marked as 2 shows that we pass the task function created in the previous section as a 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 the second argument, and the task function casts that to an integer to form the thread name. Note that we are making the call 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):
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
© 2018 sirama
karan on June 16, 2020:
crisp and clear.
FMP on June 12, 2019:
Great article, short and to the point. Thanks!
Draco on June 10, 2019:
Good article thank you :-)
Ammar The Trainer on November 30, 2018:
Nice explanation. Thanks.
Himani on October 29, 2018:
How to use events instead of Thread.Sleep ?