且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

等待池线程完成

更新时间:2023-02-09 17:48:48

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

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