前言
把異步先總結完吧。
countDownEvent 這東西是幹什麼的呢?
比如說我們比賽跑步,我們需要得出的是第一二三名得出後就可以先統計出來,因爲比較重要,後面沒有獲得獲獎名次的可以後續統計出來。
正文
static void Main(string[] args)
{
Console.WriteLine("Starting two operations");
var t1 = new Thread(() => PerformOperation("operation 1", 4));
var t2 = new Thread(() => PerformOperation("operation 1", 8));
t1.Start();
t2.Start();
_contdown.Wait();
Console.WriteLine("Both operations have been completed.");
_contdown.Dispose();
}
static CountdownEvent _contdown = new CountdownEvent(2);
static void PerformOperation(string message, int seconds)
{
Sleep(TimeSpan.FromSeconds(seconds));
Console.WriteLine(message);
_contdown.Signal();
}
在上面這個例子中,我通過使用_contdown 實例化爲等待兩個線程。
PerformOperation 中通過_contdown.Signal();來減少數量,如果減少到0的時候那麼這個時候_contdown.Wait();就可以過了。
可能我這樣解釋比較牽強吧,可以跑一下就很清晰了。
CountdownEvent 還有很多方法,可以點進去看一下,但是功能和原理差不多是這個。