ConcurrentQueue<int> queue = new ConcurrentQueue<int>(Enumerable.Range(0,10000));
CountdownEvent cde = new CountdownEvent(10000);
//This is the logic for all queue consumers
Action consumer = () =>
{
int local;
while (queue.TryDequeue(out local))
{
Console.WriteLine(Task.CurrentId.Value);
cde.Signal(); // 1万个Signal;
}
};
//Now empty the queue with a couple of asynchronous tasks
Task t1 = Task.Factory.StartNew(consumer);
Task t2 = Task.Factory.StartNew(consumer);
//And wait for queue to empty by waiting on cde
cde.Wait(); //will return when cde count reaches 0
Console.WriteLine("Done emptying queue. InitialCount={0},CurrentCount={1},IsSet={2}", cde.InitialCount, cde.CurrentCount, cde.IsSet);
Task.WaitAll(t1, t2);
CountdownEvent的使用 Task 的异步编程
最新推荐文章于 2024-06-26 20:05:44 发布