CountdownEvent用于在完成指定的几个操作后悔发出信号。 下面通过代码来说下CountdownEvent。
static CountdownEvent _countdown = new CountdownEvent(2);
static void PerformOperation(string message,int seconds)
{
Thread.Sleep(TimeSpan.FromSeconds(seconds));
Console.WriteLine(message);
_countdown.Signal();
}
static void Main(string[] args)
{
Console.WriteLine("Starting two operations");
var t1 = new Thread(() => PerformOperation("Operation 1 is completed", 4));
var t2 = new Thread(() => PerformOperation("Operation 2 is completed", 8));
t1.Start();
t2.Start();
_countdown.Wait();
Console.WriteLine("get _countdown");
_countdown.Dispose();
}
在创建CountdownEvent时可以设定需要完成几个操作时发送信号,这里我设置为两个,其含义是想要获得信号,在获得信号之前必须执行两次_countdown.Signal();
否则线程将一直处于阻塞状态,在这个程序中便是主线程想获得_countdown,必须等待t1、t2两个线程执行_countdown.Signal();
后才能获得该信号。