Thread Pool class in C#.Net

A thread pool is a collection of threads that can be used to perform a number of tasks in the background in C#.net. This leaves the primary thread free to perform other tasks asynchronously. Thread pools are often used in server applications. Each incoming request is assigned to a thread from the thread pool, so the request can be processed asynchronously, without tying up the primary thread or delaying the processing of subsequent requests.

Once a thread in the pool completes its task, it is returned to a queue of waiting threads, where it can be reused. This reuse enables applications to avoid the cost of creating a new thread for each task. Thread pools typically have a maximum number of threads. If all the threads are busy, additional tasks are placed in a queue until they can be serviced as threads become available.

Some of the useful methods to work with Thread Pool are:

  • GetAvail­ableThreads method which returns the num­ber of threads avail­able to you
  • Get­MinThreads method returns the num­ber of idle threads the thread pool main­tains in antic­i­pa­tion of new requests
  • Get­Max­Threads method returns the max num­ber of thread pool threads that can be active concurrently
  • Set­MinThreads method sets the num­ber of idle threads the thread pool main­tains in antic­i­pa­tion of new requests
  • Set­Max­Threads method sets the num­ber of thread pool threads that can be active concurrently
  • QueueUserWorkItem Queues a method for execution. The method executes when a thread pool thread becomes available
  • WaitCallback representing the method to execute

When to use Thread Pool class in C#.Net

First we will discuss, when to use thread pool class and when not to use thread pool class in C#.Net.

The situations where Thread Pool class can be applied:

  • If you have lots of logical tasks that require constant processing and you want that to be done in parallel, use thread pool class.
  • Use thread pools for database access, scripted tasks which run on virtual machines that process lots of user-defined tasks.
  • When you want to limit the number of threads running or don’t want the overhead of creating and destroying them, use a thread pool.
  • The thread pool is designed to reduce context switching among the threads. Consider a process that has several components running. Each of those components could be creating worker threads. The more threads in your process, the more time is wasted on context switching. If each of these components was queued up into the thread pool, you would have a lot less context switching overhead.
  • The thread pool is designed to maximize the work being done across your CPUs (or CPU cores). That is why, by default, the thread pool spins up multiple threads per processor.
  • Normally a pool consists of 2 threads per processor (so likely 4 nowadays), however, you can set up the number of threads you want, if you know how many you need.

The situations where one should avoid thread pool:

  • You require a foreground thread, all the thread pool threads are background threads.
  • You require a thread to have a particular priority.
  • You have tasks that cause the thread to block for long periods of time. The thread pool has a max­i­mum number of threads, so a large num­ber of blocked thread pool threads might prevent tasks from starting.
  • You need to place threads into a single-threaded apart­ment(STA). All thread pool threads are in the mul­ti­threaded apartment.
  • You need to have a stable identity associated with the thread, or to dedicate a thread to a task.
  • If you need to make your IO related tasks concurrently such as downloading stuff from remote servers or disk access, but need to do this say once every few minutes, then make your own threads and kill them once you’re finished.
  • When a thread is required to be aborted prematurely.

How to create Thread Pool via TPL in C#.Net

Now, we will discuss how to create Thread Pool via TPL in C#.Net.

The task parallel library(TPL) provides task class to enter into the thread pool easily. The task class is the part of .Net Framework 4.0. The non-generic Task class is a replacement for ThreadPool.QueueUserWorkItem and the generic Task is a replacement for asynchronous delegates.

The newer constructs are faster, more convenient, and more flexible than the old. To use the non-generic Task class, call Task.Factory.StartNew, passing in a delegate of the target method:

using System.Threading.Tasks;
using System. Threading;
using System. Diagnostics;
using System;
class tpl_threadpool
{
    static void Display()
    {
        Console.WriteLine(“Example for thread pool created by TPL…”);
    }
    static void Main() // The Task class is in System.Threading.Tasks
    {
        Task.Factory.StartNew(Display);
        Console.Read();
    }
}

How to use a Thread Pool class in C#.Net

Below is an example and code snippet on how we can use a thread pool class in C#.Net

using System;
using System. Threading;
public class ThreadPoolExample
{
   public ThreadPoolExample()
   {
      int i;
      ThreadPool.QueueUserWorkItem(new WaitCallback(C1));
      ThreadPool.QueueUserWorkItem(new WaitCallback(C2));
      for(i = 0; i < 10; i++)
      {
         Console.WriteLine(“main thread: {0}”, i);
         Thread.Sleep(500);
      }
   }
   void C1(object state)
   {
      int i;
      for (i = 0; i < 10; i++)
      {
         Console.WriteLine(”  thread1: {0}”, i);
         Thread.Sleep(1000);
      }
   }
   void C2(object state)
   {
      int i;
      for (i = 0; i < 10; i++)
      {
         Console.WriteLine(”    thread2: {0}”, i);
         Thread.Sleep(1500);
      }
   }
   public static void Main()
   {
      ThreadPoolExample tp = new ThreadPoolExample();
   }

You may like following C#.Net tutorials:

Hope this c#.net tutorial explains, What is Thread Pool class in C#.Net? How to create and use a Thread Pool class in C#.Net? Also, we learn when we should use thread pool class in c#.net.

Donwload Hub site pdf

Download SharePoint Online Tutorial PDF FREE!

Get update on Webinars, video tutorials, training courses etc.

>