本文整理汇总了C#中System.Threading.CountdownEvent类的典型用法代码示例。如果您正苦于以下问题:C# CountdownEvent类的具体用法?C# CountdownEvent怎么用?C# CountdownEvent使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
CountdownEvent类属于System.Threading命名空间,在下文中一共展示了CountdownEvent类的1个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: Main
//引入命名空间
using System;
using System.Collections.Concurrent;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
class Example
{
static async Task Main()
{
// Initialize a queue and a CountdownEvent
ConcurrentQueue<int> queue = new ConcurrentQueue<int>(Enumerable.Range(0, 10000));
CountdownEvent cde = new CountdownEvent(10000); // initial count = 10000
// This is the logic for all queue consumers
Action consumer = () =>
{
int local;
// decrement CDE count once for each element consumed from queue
while (queue.TryDequeue(out local)) cde.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);
// Proper form is to wait for the tasks to complete, even if you that their work
// is done already.
await Task.WhenAll(t1, t2);
// Resetting will cause the CountdownEvent to un-set, and resets InitialCount/CurrentCount
// to the specified value
cde.Reset(10);
// AddCount will affect the CurrentCount, but not the InitialCount
cde.AddCount(2);
Console.WriteLine("After Reset(10), AddCount(2): InitialCount={0}, CurrentCount={1}, IsSet={2}",
cde.InitialCount, cde.CurrentCount, cde.IsSet);
// Now try waiting with cancellation
CancellationTokenSource cts = new CancellationTokenSource();
cts.Cancel(); // cancels the CancellationTokenSource
try
{
cde.Wait(cts.Token);
}
catch (OperationCanceledException)
{
Console.WriteLine("cde.Wait(preCanceledToken) threw OCE, as expected");
}
finally
{
cts.Dispose();
}
// It's good to release a CountdownEvent when you're done with it.
cde.Dispose();
}
}
输出:
Done emptying queue. InitialCount=10000, CurrentCount=0, IsSet=True After Reset(10), AddCount(2): InitialCount=10, CurrentCount=12, IsSet=False cde.Wait(preCanceledToken) threw OCE, as expected