Monitor.Wait - while or if?

I am currently studying a multi-threaded exam. I read a good article on Albahari thread . I have a question when using a monitor - why is the loop used here instead of if?

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

I think if will be enough.

I am afraid that I do not fully understand the article.

// Edit Example code:

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 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!!!");
  }
}
+5
source share
5 answers

It only depends on the situation. In this case, the code just waits for _go true .

Each time it _lockerpulsates, it checks to see if it is set _goto true . If it _gois still false , it will wait for the next impulse.

if if, ( , _go true), , , _go.

, Monitor.Wait(), .

+5

. , . Monitor.Pulse(), , . , , . , - , ( while). , , (.. Monitor.Pulse()), , (... if).

+3

- if?

Pulse Wait , , while if. , , while . , ( ) , while . . while, . . :

lock (_locker)
  while ( <blocking-condition> )
    Monitor.Wait (_locker);
+1

Monitor.Wait , , "" , , , , Pulse. , , , Wait Pulse, , Wait . , Wait . " , - Pulse".

0

All Articles