.NET Reverse Semaphore?

后端 未结 8 1953
北荒
北荒 2020-12-15 17:21

Perhaps it\'s too late at night, but I can\'t think of a nice way to do this.

I\'ve started a bunch of asynchronous downloads, and I want to wait until they all comp

8条回答
  •  感情败类
    2020-12-15 18:11

    In .NET 4 there is a special type for that purpose CountdownEvent.

    Or you can build similar thing yourself like this:

    const int workItemsCount = 10;
    // Set remaining work items count to initial work items count
    int remainingWorkItems = workItemsCount;
    
    using (var countDownEvent = new ManualResetEvent(false))
    {
        for (int i = 0; i < workItemsCount; i++)
        {
            ThreadPool.QueueUserWorkItem(delegate
                                            {
                                                // Work item body
                                                // At the end signal event
                                                if (Interlocked.Decrement(ref remainingWorkItems) == 0)
                                                    countDownEvent.Set();
                                            });
        }
        // Wait for all work items to complete
        countDownEvent.WaitOne();
    }
    

提交回复
热议问题