Saturday 11 July 2015

Thread Pooling in c# .Net

A thread pool is a collection of threads that can be used to perform several tasks in the background.  This leaves the primary thread free to perform other tasks asynchronously. Once a thread in the pool completes its task, it is returned to a queue of waiting threads, where it can be reused.

Usually, the thread pool is required when we have number of threads are created to perform a number of tasks, in this organized in a queue. Typically, we have more tasks than threads. As soon as a thread completes its task, it will request the next task from the queue until all tasks have been completed. The thread can then terminate, or sleep until there are new tasks available.

Creating thread pooling

The .Net framework library included the "System.Threading.ThreadPool" class. it was so easy to use.You need not create the pool of threads, nor do you have to specify how many consuming threads you require in the pool. The ThreadPool class handles the creation of new threads and the distribution of the wares to consume amongst those threads.


  1. Via the Task Parallel Library (from Framework 4.0)
  2. By calling ThreadPool.QueueUserWorkItem
  3. Via asynchronous delegates
  4. Via BackgroundWorker



using System;
using System.Threading;

namespace TestConsole
{
    class Program
    {
        public static void Main(string[] args)
        {
             //Without passing input parameter
            ThreadPool.QueueUserWorkItem(DoLongTask);
            //With input parameter
            ThreadPool.QueueUserWorkItem(DoLongTask, "Hello");
            Console.WriteLine("Main thread ends");
            Console.ReadKey();
        }

        public static void DoLongTask(object input)
        {
            Console.WriteLine("Thread is background : {0}", Thread.CurrentThread.IsBackground);
            Console.WriteLine("Input parameter : {0}", input);
        }
    }
}


You should not use Sleep() or Join() methods if you are using ThreadPool. It may cause some unexpected behaviour. TheardPool’s threads are meant to complete the tasks as soon as possible without sleeping and in background.





In the abobe post I expalined the Thread pooling concept and I hope this post is helpful to you. Please comments your feedback and questions.

No comments:

Post a Comment