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();
}
}
}