In many situations there are tasks that can run in parallell. To create a separate thread for each such task is useful, and below is an example that makes use of WaitHandle and ThreadPool to make sure that all tasks are completed before moving on with the next step in the application.
This simple win-form application creates a thread (from now on called the taskrunner) that is to perform two separate tasks. Each task is run in a separate thread and signals to the taskrunner when they are finished. The taskrunner will wait for a predefined timeout value if given to the WaitHandle.WaitAll method.
Happy threading!
public partial class ThreadPoolWaitAllForm : Form
{
public ThreadPoolWaitAllForm()
{
InitializeComponent();
/* WaitHandle.WaitAll is not allowed on STA-thread,
* hence a thread must be created to
* perform the work needed. */
ThreadPool.QueueUserWorkItem(
delegate { PerformWork(); }
);
}
private void PerformWork()
{
/* initialize a waithandle for each thread,
* such that it can signal when
* it's work is done. */
ManualResetEvent[] waitHandlers =
new ManualResetEvent[2];
waitHandlers[0] =
new ManualResetEvent(false);
waitHandlers[1] =
new ManualResetEvent(false);
/* queue the work to be done,
* pass in reference to the waithandle
* assigned to the thread */
ThreadPool.QueueUserWorkItem(
delegate { FirstJob(waitHandlers[0]); }
);
ThreadPool.QueueUserWorkItem(
delegate { SecondJob(waitHandlers[1]); }
);
/* wait for all threads */
int timeOut = 10000;
WaitHandle.WaitAll(waitHandlers, timeOut);
MessageBox.Show("Done with work");
}
private void FirstJob(ManualResetEvent signal)
{
Thread.Sleep(1000);
signal.Set();
}
private void SecondJob(ManualResetEvent signal)
{
Thread.Sleep(1000);
signal.Set();
}
}