Spawn threads by using ThreadPool - C#

Instead of spawning a new thread each time, and killing it once it's been used, we can opt for a more efficient approach. A thread pool can be created to reuse those threads, instead of discarding them, saving time and resources.

So instead of explicitly creating the thread and calling it to perform your work:

new Thread(() => {
    Console.WriteLine("Written in a thread.");
}).Start();

We can queue the work via ThreadPool, allowing an already initialised thread to pick it up when available:

ThreadPool.QueueUserWorkItem((i) => {
    Console.WriteLine("Written inside a threadpool thread");
});

What's the difference?

The difference is subtle, but it comes with a few advantages:

  • Works well under load - A large number of threads created at once can bring a system to its knees as every task will attempt to run in parallel. The thread pool however will just queue them and take longer (still potentially a problem), running only as many asynchronously as there are threads within the pool.
  • Scales up and down automatically - Initially, the thread pool is empty. When the queue fills up, the thread pool adds new threads. When the threads haven't been used for a while, the thread pool kills them. Nice and efficient.

But with the disadvantages:

  • You cannot easily know the start or end time of the thread.
  • The local state of the thread will stay with it from one work item to another.