c#的CountdownEvent 对线程控制 https://docs.microsoft.com/zh-cn/dotnet/api/system.threading.countdownevent?view=netcore-2.1
通过 init一个初始化的计数器来管理线程,通过.Signal()让计算器减1,知道计数是0时结束wait.
using System;
using System.Threading;
using staticSystem.Threading.Thread;
using staticSystem.Console;
namespacecountdownEvent
{
class Program
{
static CountdownEvent _countdown = newCountdownEvent(2);//initial count
static void PerformOperaton(stringmessage,int secouds)
{
WriteLine("Beforesleep:"+CurrentThread.Name);
WriteLine("Beforesingal:" + _countdown.CurrentCount);
Sleep(TimeSpan.FromSeconds(secouds));
WriteLine(message);
WriteLine("Aftersleep:"+CurrentThread.Name);
_countdown.Signal(); // count -1
WriteLine("After singal:"+ _countdown.CurrentCount);
}
static void Main(string[] args)
{
Console.WriteLine("Start twooperations!");
var t1 = new Thread(() =>PerformOperaton("Operation 1 is completed",4));
var t2 = new Thread(()=>PerformOperaton("Operation 2 is completed!",8));
t1.Name = "t1";
t2.Name = "t2";
t1.Start();
t2.Start();
_countdown.Wait();//util to 0;
WriteLine("Both operations has beencompleted!");
_countdown.Dispose();
}
}
}
Start twooperations!
Before sleep:t2
Before sleep:t1
Before singal:2
Before singal:2
Operation 1 iscompleted
After sleep:t1
After singal:1
The thread 14396 hasexited with code 0 (0x0).
Operation 2 iscompleted!
After sleep:t2
After singal:0
The thread 9520 hasexited with code 0 (0x0).
Bothoperations has been completed!