Hi
I have 10 tasks grouped in two categories, CategoryA with 5 tasks and
CategoryB with 5 tasks.
I have to run all tasks in the CategoryA simultaneous and wait for it
to complete before moving on to the CategoryB.
To achieve this I start 5 background threads to execute all tasks in
the CategoryA and put main thread to sleep.
Now my question is, how do I check all background threads executing
tasks in the CategoryA are completed?
Any help would be really appreciated
Many Thanks
Niju
You can use BackgroundWorker class, and do NOT put main thread to
sleep, because you can do sync using events in BackgroundWorker class,
or
You can use ThreadPool class and do whatever you like
programmatically:
// job A
public static class A
{
private static WaitHandle[] waitHandles = new AutoResetEvent[]
{ new AutoResetEvent(false), new AutoResetEvent(false), new
AutoResetEvent(false), new AutoResetEvent(false), new AutoResetEvent
(false) };
public static void Generate(object sync)
{
AutoResetEvent waitHandle = (AutoResetEvent) sync;
Run();
waitHandle.Set();
}
private static void Run()
{
// do work A
}
}
// job B
public static class B
{
private static WaitHandle[] waitHandles = new AutoResetEvent[]
{ new AutoResetEvent(false), new AutoResetEvent(false), new
AutoResetEvent(false), new AutoResetEvent(false), new AutoResetEvent
(false) };
public static void Generate(object sync)
{
AutoResetEvent waitHandle = (AutoResetEvent) sync;
// do work B
waitHandle.Set();
}
private static void Run()
{
// do work A
}
}
// main thread
public static class Program
{
public static void Run()
{
// execute job A
for (int i = 0; i < A.waitHandles.Length; i++)
{
ThreadPool.QueueUserWorkItem(new WaitCallback
(A.Generate), A.waitHandles
);
}
// wait for all tasks in job A to complete
WaitHandle.WaitAll(A.waitHandles);
// execute job B
for (int i = 0; i < B.waitHandles.Length; i++)
{
ThreadPool.QueueUserWorkItem(new WaitCallback
(B.Generate), B.waitHandles);
}
// wait for all tasks in job B to complete
WaitHandle.WaitAll(B.waitHandles);
}
}