2009-11-02 64 views
2

我有一個線程數組,我想用超時加入它們(即查看它們是否在特定的超時時間內全部完成)。我正在尋找等價於WaitForMultipleObjects的東西或者將線程句柄傳遞到WaitHandle.WaitAll的方法,但我似乎無法在BCL中找到任何我想要的東西。Thread.Join在多個線程超時

我當然可以遍歷所有的線程(見下文),但它意味着整個函數可能需要timeout * threads.Count來返回。

private Thread[] threads; 

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

回答

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

認爲我可能最終不得不這樣做,但希望可能有一個不錯的BCL功能已經爲我做了 – 2009-11-02 15:46:25

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