Wait for pooled threads to complete

后端 未结 9 630
无人及你
无人及你 2020-12-01 01:35

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, he

9条回答
  •  一生所求
    2020-12-01 02:04

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

提交回复
热议问题