Thread.Join在多个线程上超时

Mar*_*ath 2 c# multithreading

我有一个线程数组,我想加入它们所有的超时(即看看它们是否都在一定的超时内完成).我正在寻找等同于WaitForMultipleObjects的东西或者将线程句柄传递给WaitHandle.WaitAll的方法,但我似乎无法在BCL中找到任何我想要的东西.

我当然可以遍历所有线程(见下文),但这意味着整个函数可能需要超时*threads.Count才能返回.

private Thread[] threads;

public bool HaveAllThreadsFinished(Timespan timeout)
{
     foreach (var thread in threads)
     {
        if (!thread.Join(timeout))
        {
            return false;
        }                
     }
     return true;
}
Run Code Online (Sandbox Code Playgroud)

Vit*_*sky 5

但在这个循环中,您可以减少超时值:

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;
}
Run Code Online (Sandbox Code Playgroud)


Jon*_*eet 5

我建议你最初计算出"掉线时间",然后使用当前时间和原始下降死区时间之间的差异来循环遍历线程:

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;
}
Run Code Online (Sandbox Code Playgroud)