title: c# lock statement performance
body: <p>Update - I have found the cause of <code>lock()</code> eating CPU cycles like crazy. I added this information after my original question. This all turned out to be a wall of text so:</p>
  
  <p><strong>TL;DR</strong>
  The c# built-in <code>lock()</code> mechanism will, under some circumstances, use an unusual amount of CPU time if your system is running with a high resolution system timer.</p>
  
  <p>Original question:</p>
  
  <p>I have an application that accesses a resource from multiple threads. The resource is a device attached to USB. Its a simple command/response interface and I use a small <code>lock()</code> block to ensure that the thread that sends a command also gets the response.
  My implementation uses the <code>lock(obj)</code> keyword:</p>
  
  <pre><code>lock (threadLock)
  {
      WriteLine(commandString);
      rawResponse = ReadLine();
  }
  </code></pre>
  
  <p>When I access this from 3 threads as fast as possible (in a tight loop) the CPU usage is about 24% on a high-end computer. Due to the nature of the USB port only about 1000 command/response operations are performed per second.
  Then I implemented the lock mechanism described here <a href="http://www.adammil.net/blog/v111_Creating_High-Performance_Locks_and_Lock-free_Code_for_NET_.html" rel="nofollow noreferrer">SimpleExclusiveLock</a> and the code now looks similar to this (some <code>try</code>/<code>catch</code> stuff to release the lock in case of an I/O exception is removed):</p>
  
  <pre><code>Lock.Enter();
  WriteLine(commandString);
  rawResponse = ReadLine();
  Lock.Exit();
  </code></pre>
  
  <p>Using this implementation the CPU usage drops to &lt;1% with the same 3 thread test program while still getting the 1000 command/response operations per second.</p>
  
  <p><strong>The question is: What, in this case, is the problem using the built-in <code>lock()</code> keyword?</strong> </p>
  
  <p>Have I accidentally stumbled upon a case where the <code>lock()</code> mechanism has exceptionally high overhead? The thread that enters the critical section will hold the lock for only about 1 ms.</p>
  
  <p><strong>Update:</strong>
  The cause of <code>lock()</code> eating CPU like crazy is that some application has increased the timer resolution for the whole system using <code>timeBeginPeriod()</code> in winmm.dll. The culprits in my case are Google Chrome and SQL Server - they requested a 1 ms system timer resolution using:</p>
  
  <pre><code>[DllImport("winmm.dll", EntryPoint = "timeBeginPeriod", SetLastError = true)]
  private static extern uint TimeBeginPeriod(uint uMilliseconds);
  </code></pre>
  
  <p>I found this out by using the powercfg tool:</p>
  
  <pre><code>powercfg -energy duration 5 
  </code></pre>
  
  <p>Due to some sort of design flaw in the built-in <code>lock()</code> statement this increased timer resolution eats CPU like crazy (at least in my case). 
  So, I killed the programs that request high resolution system timer. My application now runs a bit slower. Each request will now lock for 16.5 ms instead of 1 ms. The reason behind that I guess is that the threads are scheduled less frequently. The CPU usage (as shown in Task Manager) also dropped to zero. I have no doubt that <code>lock()</code> still uses quite a few cycles but that is now hidden. </p>
  
  <p>In my project low CPU use is an important design factor. The low 1 ms latency of USB requests are also positive for the overall design. So (in my case) the solution is to discard the built-in <code>lock()</code> and replace it with a properly implemented lock mechanism. I already threw out the flawed <code>System.IO.Ports.SerialPort</code> in favor of WinUSB so I have no fears :)</p>
  
  <p>I made a small console-application to demonstrate all of this, pm me if you are interested in a copy (~100 lines of code).</p>
  
  <p>I guess I answered my own question so I´ll just leave this here in case someone is interested...</p>