开发者

Thread.Join on multiple threads with timeout

开发者 https://www.devze.com 2022-12-10 04:59 出处:网络
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

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;
}


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;
}


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;
}


if(!thread.Join(End-now)) 
    return false; 

See C#: Waiting for all threads to complete

0

精彩评论

暂无评论...
验证码 换一张
取 消