views:

269

answers:

3

I have an array of threads, and I want to Join them all with a timeout (i.e. see if they have all finished within a certain timeout). I'm looking for something equivalent to WaitForMultipleObjects or a way of passing the thread handles into WaitHandle.WaitAll, but I can't seem to find anything in the BCL that does what I want.

I can of course loop through all the threads (see below), but it means that the overall function could take timeout * threads.Count to return.

private Thread[] threads;

public bool HaveAllThreadsFinished(Timespan timeout)
{
     foreach (var thread in threads)
     {
        if (!thread.Join(timeout))
        {
            return false;
        }                
     }
     return true;
}
+3  A: 

But within this loop you can decrease timeout value:

private Thread[] threads;

public bool HaveAllThreadsFinished(Timespan timeout)
{
     foreach (var thread in threads)
     {
        Stopwatch sw = Stopwatch.StartNew();
        if (!thread.Join(timeout))
        {
            return false;
        }
        sw.Stop();
        timeout -= Timespan.FromMiliseconds(sw.ElapsedMiliseconds);                
     }
     return true;
}
Vitaliy Liptchinsky
thought I might end up having to do this, but was hoping there might be a nice BCL function already that does it for me
Mark Heath
+2  A: 
if(!thread.Join(End-now)) 
    return false;

See http://stackoverflow.com/questions/263116/c-waiting-for-all-threads-to-complete

Mark Byers
+1  A: 

I suggest you initially work out the "drop dead time" and then loop over the threads, using the difference between the current time and the original drop dead time:

private Thread[] threads;

public bool HaveAllThreadsFinished(Timespan timeout)
{
     DateTime end = DateTime.UtcNow + timeout;

     foreach (var thread in threads)
     {
        timeout = end - DateTime.UtcNow;
        if (timeout <= TimeSpan.Zero || !thread.Join(timeout)) {
            return false;
        }                
     }
     return true;
}
Jon Skeet
Tony, you seem to have climbed the rep ladder awful fast. Coincidentally, I don't see Jon in the rankings anymore. Hmmm...
Michael Petrotta