线程通过调用 AutoResetEvent 上的 WaitOne 来等待信号,通过调用 Set 发出资源可用的信号。可以通过将一个布尔值传递给构造函数来控制 AutoResetEvent 的初始状态,如果初始状态为终止状态,则为 true;否则为 false。

private static readonly AutoResetEvent _workerEvent = new(false);
private static readonly AutoResetEvent _mainEvent = new(false);
static void Main(string[] args)
{
  new Thread(() => Process(10)).Start();
  Console.WriteLine("1、等待另一个线程完成其工作 Waiting for another thread to complete its work");
  _workerEvent.WaitOne();
  Console.WriteLine("5、第一次操作完成! First operation is completed!");
  Console.WriteLine("6、在主线程上执行操作 Performing an operation on a main thread");
  Thread.Sleep(TimeSpan.FromSeconds(5));
  _mainEvent.Set();
  Console.WriteLine("7、现在在第二个线程上运行第二个操作 Now running the second operation on a second thread");
  _workerEvent.WaitOne();
  Console.WriteLine("10、第二个操作已完成! Second operation is completed!");
}

static void Process(int seconds)
{
  Console.WriteLine("2、开始一项长期的工作 ... Starting a long running work ...");
  Thread.Sleep(TimeSpan.FromSeconds(seconds));
  Console.WriteLine("3、工作完成了! Work is done!");
  _workerEvent.Set();
  Console.WriteLine("4、等待主线程完成其工作 Waiting for a main thread to complete its work");
  _mainEvent.WaitOne();
  Console.WriteLine("8、正在启动第二个操作 ... Starting second operation ...");
  Thread.Sleep(TimeSpan.FromSeconds(seconds));
  Console.WriteLine("9、工作完成了! Work is done!");
  _workerEvent.Set();
}