Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>100 is far too few, and running in a test framework may skew things. It is also possibly (see comments) related to any additional cost associated with the <em>first</em> lock against an object; try:</p> <ul> <li>locking once outside the loop first</li> <li>doing lots more iterations</li> <li>in a console exe, at the command line, in release mode</li> </ul> <p>Also, note that in 4.0 <code>lock</code> is <strong>not</strong> <code>Monitor.Enter(object)</code> - so expect different results in 4.0.</p> <p>But I get:</p> <pre><code>lock: 3548ms Monitor.TryEnter: 7008ms Monitor.TryEnter (2): 2947ms Monitor.Enter: 2906ms </code></pre> <p>From the test rig:</p> <pre><code>using System; using System.Diagnostics; using System.Threading; static class Program { static void Main() { const int lockIterations = 50000000; object object1 = new object(); lock (object1) { Console.WriteLine("First one has to pay an extra toll"); } Stopwatch csLock = Stopwatch.StartNew(); for (int i = 0; i &lt; lockIterations; ) { lock (object1) { i++; } } csLock.Stop(); Console.WriteLine("lock: " + csLock.ElapsedMilliseconds + "ms"); Stopwatch csMonitorTryEnter = Stopwatch.StartNew(); for (int i = 0; i &lt; lockIterations; ) { if (Monitor.TryEnter(object1, TimeSpan.FromSeconds(10))) { try { i++; } finally { Monitor.Exit(object1); } } } csMonitorTryEnter.Stop(); Console.WriteLine("Monitor.TryEnter: " + csMonitorTryEnter.ElapsedMilliseconds + "ms"); csMonitorTryEnter = Stopwatch.StartNew(); for (int i = 0; i &lt; lockIterations; ) { if (Monitor.TryEnter(object1, 10000)) { try { i++; } finally { Monitor.Exit(object1); } } } csMonitorTryEnter.Stop(); Console.WriteLine("Monitor.TryEnter (2): " + csMonitorTryEnter.ElapsedMilliseconds + "ms"); Stopwatch csMonitorEnter = Stopwatch.StartNew(); for (int i = 0; i &lt; lockIterations; ) { Monitor.Enter(object1); try { i++; } finally { Monitor.Exit(object1); } } csMonitorEnter.Stop(); Console.WriteLine("Monitor.Enter: " + csMonitorEnter.ElapsedMilliseconds + "ms"); } } </code></pre>
    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.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. 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