CountdownEvent主要是用來等待直到一定數量的執行緒完成。
以下範例有三個執行緒,但等待兩個完成後即可繼續往下執行。
程式碼如下:
using System;
using System.Threading;
namespace ConsoleApp1
{
class Program
{
//等待一定數量完成才繼續往下執行,在這邊設定等待2個執行緒完成
static CountdownEvent _event = new CountdownEvent(2);
static void PerformOperation(string message,int seconds)
{
try
{
Thread.Sleep(TimeSpan.FromSeconds(seconds));
Console.WriteLine(message);
//發送信號計數+1
_event.Signal();
}
catch(System.ObjectDisposedException)
{
Console.WriteLine("CountdownEvent has disposed");
}
}
static void Main(string[] args)
{
Thread t1 = new Thread(() => { PerformOperation("operation 1 is completed.",2); });
t1.Name = "t1";
Thread t2 = new Thread(() => { PerformOperation("operation 2 is completed.", 4); });
t2.Name = "t2";
Thread t3 = new Thread(() => { PerformOperation("operation 3 is completed.", 12); });
t3.Name = "t3";
t1.Start();
t2.Start();
t3.Start();
//開始等待完成
_event.Wait();
Console.WriteLine("有兩個已完成!");
_event.Dispose();
Console.WriteLine("繼續往下執行...");
Console.ReadKey();
}
}
}
打印結果如下:
沒有留言:
張貼留言