C#中:等待所有线程完成 [英] C#: Waiting for all threads to complete

查看:802
本文介绍了C#中:等待所有线程完成的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我运行到了code,我正在写,我需要等待所有的线程组中来完成,一个超时的通用模式。超时应该是需要时间的所有的线程来完成,因此简单地做的Thread.join(超时)为每个线程将无法正常工作,因为可能超时,然后是超时* 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.

现在我做类似以下内容:

Right now I do something like the following:

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.

推荐答案

我还是觉得用加入更简单。记录预期完成时间(如现在+超时),那么,在一个循环中,执行

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆