等待池线程完成 [英] Wait for pooled threads to complete

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

问题描述

我很抱歉冗余问题。然而,我发现许多解决我的问题,但他们都不是很好的解释。我希望,这将是明确表示,在这里。

I'm sorry for a redundant question. However, I've found many solutions to my problem but none of them are very well explained. I'm hoping that it will be made clear, here.

我的C#应用​​程序的主线程派生1..N使用线程池背景的工人。我想,原始线程锁定,直到所有工人已经完成。我已经研究了ManualResetEvent的特别,但我并不清楚它的用途。

My C# application's main thread spawns 1..n background workers using the ThreadPool. I wish for the original thread to lock until all of the workers have completed. I have researched the ManualResetEvent in particular but I'm not clear on it's use.

在伪:

foreach( var o in collection )
{
  queue new worker(o);
}

while( workers not completed ) { continue; }

如果有必要

,我会知道工人是大约前手被排队的数目

If necessary, I will know the number of workers that are about to be queued before hand.

推荐答案

试试这个。该函数在行动代表的名单。这将增加对列表中的每个项目一个线程池工的进入。它会等待每一个动作在返回前完成。

Try this. The function takes in a list of Action delegates. It will add a ThreadPool worker entry for each item in the list. It will wait for every action to complete before returning.

public static void SpawnAndWait(IEnumerable<Action> actions)
{
    var list = actions.ToList();
    var handles = new ManualResetEvent[actions.Count()];
    for (var i = 0; i < list.Count; i++)
    {
        handles[i] = new ManualResetEvent(false);
        var currentAction = list[i];
        var currentHandle = handles[i];
        Action wrappedAction = () => { try { currentAction(); } finally { currentHandle.Set(); } };
        ThreadPool.QueueUserWorkItem(x => wrappedAction());
    }

    WaitHandle.WaitAll(handles);
}

这篇关于等待池线程完成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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