just want some advice on \"best practice\" regarding multi-threading tasks.
as an example, we have a C# application that upon startup reads data from various \"type
Here are two patterns for waiting on multiple parallel operations. The trick is that you have to treat your main thread as if it were one of the parallel operations as well. Otherwise, there is a subtle race condition between the signalling of completion in the worker threads and the waiting on that signal from the main thread.
int threadCount = 1;
ManualResetEvent finished = new ManualResetEvent(false);
for (int i = 0; i < NUM_WORK_ITEMS; i++)
{
Interlocked.Increment(ref threadCount);
ThreadPool.QueueUserWorkItem(delegate
{
try
{
// do work
}
finally
{
if (Interlocked.Decrement(ref threadCount) == 0) finished.Set();
}
});
}
if (Interlocked.Decrement(ref threadCount) == 0) finished.Set();
finished.WaitOne();
As a personal preference I like using the CountdownEvent class to do the counting for me which is available in .NET 4.0.
var finished = new CountdownEvent(1);
for (int i = 0; i < NUM_WORK_ITEMS; i++)
{
finished.AddCount();
ThreadPool.QueueUserWorkItem(delegate
{
try
{
// do work
}
finally
{
finished.Signal();
}
});
}
finished.Signal();
finished.Wait();
The examples above use the ThreadPool, but you can swap that for whatever threading mechanism you prefer.