Home > DeveloperSection > Articles > ThreadPool in C# Programming

ThreadPool in C# Programming

C# C# 
0 Comment(s)
 20039  View(s)
Rate this:

ThreadPool in C# Programming

ThreadPool is an efficient way through which we can process jobs in parallel in C# programming language. ThreadPool is a collection of threads that can be used to perform many tasks in background i.e. we can say that ThreadPool Provides a pool of threads that can be used to execute tasks, post work items, process asynchronous I/O and wait on behalf of other threads etc.

Thread pools are often employed 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.

Thread pools typically have a maximum number of threads. If all the threads are busy, additional tasks are placed in queue until they can be serviced as threads become available.

Here I am giving an example of ThreadPool class.  Let’s see the brief demonstration of example.


using System.Threading;

using System.Diagnostics;


namespace PoolThread


    class MyProcess


        public ManualResetEventdoneEvent;


        publicMyProcess(ManualResetEvent sendEvent)


        // Assign notify event from ThreadPool




       public void MyProcessThreadPoolCallback(Objectindex)


            int threadIndex= (int)index;

         Console.WriteLine("thread {0} started...", threadIndex);

        // Call the process that is created on every thread


         Console.WriteLine("thread {0} end...", threadIndex);


        // Indicates that the process has been completed




// Start any process

    public void StartProcess()


        // Start process that open c:\ directory






public class ThreadPoolExample


     static voidMain()


         const inttotalCountProcess=10;

         // Create manualresetevent array to assign with process

         ManualResetEvent[] sendEvents= new ManualResetEvent[totalCountProcess];

         // Create MyProcess objects array

         MyProcess[] MyProcessArray=new MyProcess[totalCountProcess];


         // Configure and launch threads using ThreadPool:

         Console.WriteLine("launching thread...");

         for (inti=0; i<totalCountProcess ; i++)


             sendEvents[i] = new ManualResetEvent(false);

             MyProcess p= newMyProcess(sendEvents[i]);

             MyProcessArray[i] =p;

             // ThreadPool call QueueUserWorkItem method to execute when ThreadPool having thread

             ThreadPool.QueueUserWorkItem(p.MyProcessThreadPoolCallback, i);

             // After execute one thread it go in sleep mode for 2 second



         // Wait for all thread to complete execution


         Console.WriteLine("All process are complete.");







Desired Output:

Don't want to miss updates? Please click the below button!

Follow MindStick