Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>A problem with <code>Monitor.Pulse/Wait</code> is that the signal may get lost.</p> <p>For example:</p> <pre><code>var signal = new ManualResetEvent(false); // Thread 1 signal.WaitOne(); // Thread 2 signal.Set(); </code></pre> <p>This will always work no matter in which the two statements in the different threads are executed. It's also a very clean abstraction and expresses very clearly your intent.</p> <p>Now have a look at the same example using a monitor:</p> <pre><code>var signal = new object(); // Thread 1 lock (signal) { Monitor.Wait(signal); } // Thread 2 lock (signal) { Monitor.Pulse(signal); } </code></pre> <p>Here the signal (<code>Pulse</code>) will get lost if <code>Pulse</code> is executed before <code>Wait</code>.</p> <p>To fix this problem, you need something like this:</p> <pre><code>var signal = new object(); var signalSet = false; // Thread 1 lock (signal) { while (!signalSet) { Monitor.Wait(signal); } } // Thread 2 lock (signal) { signalSet = true; Monitor.Pulse(signal); } </code></pre> <p>This works and is probably even more performant and lightweight, but is less readable. And it's where the headache called concurrency starts.</p> <ul> <li>Does this code really work?</li> <li>In every corner case?</li> <li>With more than two threads? <em>(Hint: it doesn't)</em></li> <li>How do you unit-test it?</li> </ul> <p><strong>A solid, reliable, readable abstraction is often better than raw performance.</strong></p> <p>Additionally, WaitHandles provide some nice stuff like waiting for a set of handles to be set, etc. Implementing this with monitors makes the headache even worse...</p> <hr> <p>Rule of thumb:</p> <ul> <li>Use <strong>Monitors</strong> (<code>lock</code>) to ensure exclusive access to a shared resource</li> <li>Use <strong>WaitHandles</strong> (Manual/AutoResetEvent/Semaphore) to send signals between threads</li> </ul>
 

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