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;
}
Mark Heath
  • 48,273
  • 29
  • 137
  • 194

3 Answers3

5

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
  • 5,221
  • 2
  • 18
  • 25
  • 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 Nov 02 '09 at 15:46
  • I think Timespan is `TimeSpan`, FromMiliseconds is `FromMilliseconds`, and ElapsedMiliseconds is `ElapsedMilliseconds`. – Jonathan Jun 23 '21 at 17:14
5

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
  • 1,421,763
  • 867
  • 9,128
  • 9,194
2
if(!thread.Join(End-now)) 
    return false; 

See C#: Waiting for all threads to complete

Community
  • 1
  • 1
Mark Byers
  • 811,555
  • 193
  • 1,581
  • 1,452