C#:等待所有线程完成 [英] C#: Waiting for all threads to complete
问题描述
我在编写的代码中遇到了一个常见模式,我需要等待组中的所有线程完成并超时.超时应该是所有线程完成所需的时间,所以简单地为每个线程执行 thread.Join(timeout) 是行不通的,因为可能的超时时间是 timeout * numThreads.
I'm running into a common pattern in the code that I'm writing, where I need to wait for all threads in a group to complete, with a timeout. The timeout is supposed to be the time required for all threads to complete, so simply doing thread.Join(timeout) for each thread won't work, since the possible timeout is then timeout * numThreads.
现在我做的事情如下:
var threadFinishEvents = new List<EventWaitHandle>();
foreach (DataObject data in dataList)
{
// Create local variables for the thread delegate
var threadFinish = new EventWaitHandle(false, EventResetMode.ManualReset);
threadFinishEvents.Add(threadFinish);
var localData = (DataObject) data.Clone();
var thread = new Thread(
delegate()
{
DoThreadStuff(localData);
threadFinish.Set();
}
);
thread.Start();
}
Mutex.WaitAll(threadFinishEvents.ToArray(), timeout);
但是,对于这种事情,似乎应该有一个更简单的习语.
However, it seems like there should be a simpler idiom for this sort of thing.
推荐答案
我仍然认为使用 Join 更简单.记录预期完成时间(如Now+timeout),然后循环执行
I still think using Join is simpler. Record the expected completion time (as Now+timeout), then, in a loop, do
if(!thread.Join(End-now))
throw new NotFinishedInTime();
这篇关于C#:等待所有线程完成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!