Thread Pool - C#โŒš๐Ÿ’ฅ

Thread Pool - C#โŒš๐Ÿ’ฅ

ยท

3 min read

What is Thread Pool?

Creating thread can be helpful to improve performance but too much of it will degrade the performance drastically. Here comes the solution named Thread pool.

Thread pool is a collection of threads pre-created only. So when our application starts it gets a ready-made thread pool with a number of threads in it. Normally it depends on the Core. Like if you have 1 core CPU the default number of threads will be 2. In the thread pool, all of the threads are background threads.

Why do we need it?

Working with thread, come with some difficult challenges in it such as creating, scheduling, monitoring, etc. If we use thread pool we won't have to do any of the work at all, the mighty thread pool does that for us, we just need to ask for the thread from the thread pool to execute some heavy tasks.

Example:

This is how we can create threads.

Thread thread1 = new Thread(() => DoSomeWork);
thread1.Start();

So let's see how we can use a Thread pool to work around it.

Threadpool.QueueUserWorkItem(() => DoSomeWork);

private static DoSomeWork() 
{
    for (int i = 0; i < 100_00_00; i++) 
    {
        // Doing some heavy work ๐ŸŽ‰
    }
}

Usage:

There is a number of ways to use a thread pool.

  1. Via TPL (Task Parallel Library)
  2. By accessing directly ThreadPool class.
  3. By Async Delegates.
  4. By Background worker.

You may ask the question then the how HTTP request processing works or how request call thread pool?

So normally without using a thread pool, a thread life cycle works like this.

image.png

If we are going to use thread pool then the life cycle looks like this.

image.png

The magic underneath:

The magic is, when an application starts, a thread pool is automatically created with the number of threads pre-created on it. When a request intercepts to the thread pool, it just picks a thread from the pool, processes the request, and returns the thread to the pool to sit idle. It does not destroy the thread. Creating threads in the .net ecosystem is expensive in terms of memory. We handle this over to the thread pool itself.

So in the bigger picture, this is how it looks like:

image.png

Benefits:

  1. Improve response time of an app as the app doesn't need to maintain thread life cycle and the required thread is already ready to use by the pool.
  2. We can start several tasks without having to worry about configuring the thread and its properties, everything is managed by the pool already.
  3. When needed extra thread if the maximum thread is occupied in the pool, the pool automatically creates the required thread and executes the tasks.