Thread.Join 在多个线程上超时 [英] Thread.Join on multiple threads with timeout
问题描述
我有一个线程数组,我想在超时的情况下将它们全部加入(即查看它们是否都在某个超时内完成).我正在寻找等效于 WaitForMultipleObjects 的东西或将线程句柄传递到 WaitHandle.WaitAll 的方法,但我似乎无法在 BCL 中找到任何我想要的东西.
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.
我当然可以遍历所有线程(见下文),但这意味着整个函数可能需要 timeout *thread.Count 才能返回.
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;
}
这篇关于Thread.Join 在多个线程上超时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!