How to use thread pooling in C#


Introduction:
Here, In this articles we will see how to use Thread pooling  in C#
A Thread Pooling is created to perform multiple task simultaneously. a thread pool basically a group of threads that can be run simultaneously to perform a number of task in the background. This feature of C# is mainly used in server application. in server application a main threads receive the request from the client computer and passes it to a thread in the thread pool for processing of the request from the client computers. A thread pool may contain a number of threads each performing a specific task. if all the threads in a thread pool are occupied in performing there task then a new task, which need to be processed wait in a queue until a thread becomes free.net framework provides thread pool through the threadpool class. we can implement a custom thread pool in threadpool class.
50 different threads at different intervals of time and subsequently stops all threads one by one after period of 5 seconds, where each thread is made to wait for 5seconds. 


Example: 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace Threadpooling
{
class ThreadPoolTest
{
static object showThread = new object();
static int runThreads = 50;
public static void Main()
{
for (int i = 0; i < runThreads; i++)
{
ThreadPool.QueueUserWorkItem(Display, i);
}
Console.WriteLine("running 50 threads to one by one and stopping them after 5secounds.\n");
lock (showThread)
{
while (runThreads > 0) Monitor.Wait(showThread);
}
Console.WriteLine("All Threads stopped sucessfully");
Console.ReadLine();
}
public static void Display(object threadobj)
{
Console.WriteLine("started thread:" +threadobj);
Thread.Sleep(3000);
Console.WriteLine("ended thread:"+threadobj);
lock(showThread)
{
Monitor.Pulse(showThread);
}
}
}
}
 Output of program :

thread.gif

Thank U. if U have any Suggestions and Comments about my blog, Plz let me know.