Thread.Join在多个线程上超时

时间:2009-11-02 15:25:35

标签: 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;
}

3 个答案:

答案 0 :(得分: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;
}

答案 1 :(得分:4)

但是在这个循环中你可以减少超时值:

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

答案 2 :(得分:2)

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

请参阅C#: Waiting for all threads to complete