What's the best practice for detecting when a whole group of threads are done processing? I have a process that will query a [long running] web service for an arbitrary number of objects, and then needs to take a transactional action when all of them have completed successfully. I am currently running them asynchronously, using delegates from the .Net thread pool. Running them synchronously, defeats the purpose of running them on multiple threads... How else can I detect when ALL are finished? I though of using a coounter, (aka COM referece count) incrementing it for reach thread that starts and decrementing it in a callback function, and of keeping a dynamic list with a reference to each thread in it, to explicitly keep track of each one as they complete, but both of these solutions seem kinda kludgy...
Thanks to all... Based on yr suggestions, and on need to pass an object instance to the aynchronous thread, (represented by ref variable uPL below), I am using the following code... NOTE: IEEDAL.GetUsagePayloadReadings(uPL1) is the remote web service call
foreach (MeterChannel chgChan in chgChs)
foreach (UsagePayload uPL in chgChan.IntervalPayloads)
{
ManualResetEvent txEvnt = new ManualResetEvent(false);
UsagePayload uPL1 = uPL;
ThreadPool.QueueUserWorkItem(
delegate(object state)
{
if (!uPL1.HasData)
IEEDAL.GetUsagePayloadReadings(uPL1);
UsageCache.PersistPayload(uPL1);
SavePayLoadToProcessFolder(uPL1);
txEvnt.Set();
} );
waitHndls.Add(txEvnt);
}
WaitHandle.WaitAll(waitHndls.ToArray());