Monitor.Wait - while或if?

bit*_*ler 5 c# multithreading monitor

目前,我正在学习多线程考试.我读了阿尔巴哈里的好文章.我在监视器的使用上有一个问题 - 为什么在这里使用循环代替if?

lock (_locker)
{
  while (!_go) //why while and not if?
    Monitor.Wait (_locker);  // _lock is released
  // lock is regained
  ...
}
Run Code Online (Sandbox Code Playgroud)

我认为,一个if就足够了.

我很害怕,我完全不理解这篇文章.

//编辑示例代码:

class SimpleWaitPulse
{
  static readonly object _locker = new object();
  static bool _go;

  static void Main()
  {                                // The new thread will block
    new Thread (Work).Start();     // because _go==false.

    Console.ReadLine();            // Wait for user to hit Enter

    lock (_locker)                 // Let's now wake up the thread by
    {                              // setting _go=true and pulsing.
      _go = true;
      Monitor.Pulse (_locker);
    }
  }

  static void Work()
  {
    lock (_locker)
      while (!_go)
        Monitor.Wait (_locker);    // Lock is released while we’re waiting

    Console.WriteLine ("Woken!!!");
  }
}
Run Code Online (Sandbox Code Playgroud)

Igb*_*man 5

这取决于具体情况.在这种情况下,代码只是等待_go成为现实.

每次_locker脉冲都会检查是否_go已设置为.如果_go仍为,它将等待下一个脉冲.

如果使用if而不是while,它只会等待一次(或者如果_go已经为则不会),然后在脉冲之后继续执行,无论新的状态如何_go.

所以你如何使用Monitor.Wait()完全取决于你的具体需求.