CountdownEvent 计数 监听 指定数量的线程,没完成一个线程Signal()计数一次,直到全部完成,才会继续执行Wait()下面的任务。

static readonly CountdownEvent _contdown = new (2);// 创建2个数量

static void Main(string[] args)
{
  _contdown.Reset(3);// 重置为3个数量

  Console.WriteLine("Starting two operations");
  new Thread(() => PerformOperation("A", 2)).Start();
  new Thread(() => PerformOperation("B", 6)).Start();
  new Thread(() => PerformOperation("C", 8)).Start();
  _contdown.Wait();// 等待3个线程都完成
  Console.WriteLine("Both operations have been completed.");
  _contdown.Dispose();
}

static void PerformOperation(string message, int seconds)
{
  Console.WriteLine(message);
  Thread.Sleep(TimeSpan.FromSeconds(seconds));
  _contdown.Signal();// 通知已经有一个线程完成了
}