Reader Level:
ARTICLE

ThreadPool class in .NET

Posted by Ashish Shukla Articles | C# Language April 18, 2011
This article describes the use of the ThreadPool class in .NET.
  • 0
  • 0
  • 5843

ThreadPooling

Multithreading is used to perform some tasks in the background typically so that the main application thread or UI thread is not blocked. But there is an overhead involved to create new threads and if the operations performed by these threads are quite simple then the creation and destruction of new threads can have impact on the performance of the system.

The ThreadPool class in the System.Threading namespace can be used if we are required to create large number of threads. ThreadPool is a collection of threads which can be used and returned to the pool once the processing is complete.

Following diagram illustrates the how threads are used from the ThreadPool :

ThreadPool1.gif

In the above diagram there are three requests in the Requests Queue and two threads in the thread pool, in such a scenario the extra request waits its turn in the requests queue till the thread becomes available to process it.

As soon as we create a new thread pool it creates a new thread to serve the requests and keeps on creating the new threads unitl it reaches a defined limit.

And after the thread completes its job it is not destroyed immediately instead it waits for some duration for the new request before it gets destroyed.

When a thread from the thread pool is reused the data in the thread local storage remains. Also the fields that are marked with the ThreadStaticAttribute retains there data.

But the threads in the ThreadPool are all background threads so when the foreground thread exits the
Thread also terminates.

To execute the method in the thread from the threadpool we need to pass the QueueUserWorkItem a
Waitcallback delegate instance to which we need to pass the method we have to call.The method should be marked as static and void.

class Program
    {

        static void Main(string[] args)
        {
          ThreadPool.QueueUserWorkItem (new WaitCallback(Process),null);
         }

         public static void Process(object obj)
        {
            Console.WriteLine("Background thread started ");
        }


As you see in the above code we pass null as the second parameter, in place of null we can pass the information to the method.

To check the number of threads currently available in the thread pool we can use the GetAvailableThreads method which has the following signature:

public static void GetAvailableThreads(out int workerThreads, out int completionPortThreads);

Following gets the number of available worker and IO threads.

int availableWorkers = 0;
int availableAsyncIO = 0;
ThreadPool.GetMaxThreads(out availableWorkers, out availableAsyncIO);

Once a workitem has been queued in the pool it can not be cancelled.There can be one thread pool per process.
 

COMMENT USING

Trending up