Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Consider this example:</p> <pre><code>public class EnterExitExample { private object myLock; private bool running; private void ThreadProc1() { while (running) { lock (myLock) { // Do stuff here... } Thread.Yield(); } } private void ThreadProc2() { while (running) { lock (myLock) { // Do other stuff here... } Thread.Yield(); } } } </code></pre> <p>Now you have two threads, each waiting for lock, then doing their stuff, then releasing the lock. The <code>lock (myLock)</code> syntax is just sugar for <code>Monitor.Enter(myLock)</code> and <code>Monitor.Exit(myLock)</code>.</p> <p>Let us now look at a more complicated example, where <code>Wait</code> and <code>Pulse</code> come into play.</p> <pre><code>public class PulseWaitExample { private Queue&lt;object&gt; queue; private bool running; private void ProducerThreadProc() { while (running) { object produced = ...; // Do production stuff here. lock (queue) { queue.Enqueue(produced); Monitor.Pulse(queue); } } } private void ConsumerThreadProc() { while (running) { object toBeConsumed; lock (queue) { Monitor.Wait(queue); toBeConsumed = queue.Dequeue(); } // Do consuming stuff with toBeConsumed here. } } } </code></pre> <p>What do we have here? </p> <p>The producer produces an object whenever he feels like it. As soon as he has, he obtains lock on the queue, enqueues the object, then does a <code>Pulse</code> call.</p> <p>At the same time, the consumer does NOT have lock, he left it by calling <code>Wait</code>. As soon as he gets a <code>Pulse</code> on that object, he will re-lock, and do his consuming stuff.</p> <p>So what you have here is a direct thread-to-thread notification that there is something to do for the consumer. If you wouldn't have that, all you could do is have the consumer keep polling on the collection if there is something to do yet. Using <code>Wait</code>, you can make sure that there is.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload