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.
Example:
using
System.Threading;
using
System.Diagnostics;
namespace
PoolThread
{
class
MyProcess
{
public
ManualResetEvent doneEvent;
public MyProcess(ManualResetEvent
sendEvent)
{
// Assign notify event from ThreadPool
this.doneEvent = sendEvent;
}
public
void
MyProcessThreadPoolCallback(Object
index)
{
int
threadIndex = (int)index;
Console.WriteLine("thread {0}
started...", threadIndex);
// Call the process that is created on every thread
StartProcess();
Console.WriteLine("thread {0}
end...", threadIndex);
// Indicates that the process has been completed
this.doneEvent.Set();
}
// Start any process
public
void
StartProcess()
{
// Start process that open c:\ directory
Process.Start("C:\\");
}
}
public
class
ThreadPoolExample
{
static
void Main()
{
const
int totalCountProcess = 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 (int i = 0; i < totalCountProcess ; i++)
{
sendEvents[i] =
new
ManualResetEvent(false);
MyProcess
p =
new MyProcess(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
Thread.Sleep(2000);
}
// Wait for all thread to complete execution
WaitHandle.WaitAll(sendEvents);
Console.WriteLine("All process
are complete.");
Console.ReadKey();
}
}
}
Desired Output:
|