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.

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.

So example time 🐱‍🏍

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++) { } }

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

  1. Via TPL (Task Parallel Library)

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.

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

What’s the magic about it? what is thread pool is actually doing ?

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:

What is the benefit of it ?

  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.

Originally published at https://pritompurkayasta.me.

if you like the content, you know what to do 🎉✔