ManualResetEventSlim的整个工作方式如同人群通过大门,Set() 大门敞开谁都能进出,每个人被 Wait()后,只能期待下一次Set()才能进出大门。Reset() 就是关闭大门,谁也不能进出。

static readonly ManualResetEventSlim _mainEvent = new();
static void Main(string[] args)
{
  new Thread(() => TravelThrougnGates("A", 5)).Start();
  new Thread(() => TravelThrougnGates("B", 6)).Start();
  new Thread(() => TravelThrougnGates("C", 12)).Start();

  Thread.Sleep(TimeSpan.FromSeconds(6));
  _mainEvent.Set();// 允许进出
  Thread.Sleep(TimeSpan.FromSeconds(2));
  _mainEvent.Reset();// 关门
  Console.WriteLine($"_mainEvent is not open");
  Thread.Sleep(TimeSpan.FromSeconds(10));
  Console.WriteLine($"_mainEvent is open");
  _mainEvent.Set();// 允许进出
  Thread.Sleep(TimeSpan.FromSeconds(2));
  Console.WriteLine($"_main enter");
}

static void TravelThrougnGates(string Threadname, int second)
{
  Console.WriteLine($"{Threadname} start sleep");
  Thread.Sleep(TimeSpan.FromSeconds(second));
  Console.WriteLine($"{Threadname} start running");
  _mainEvent.Wait();// 等待
  Console.WriteLine($"{Threadname} enter gate");
}