title: Is Interlocked.CompareExchange really faster than a simple lock?
body: <p>I came across a <code>ConcurrentDictionary</code> implementation for .NET 3.5 (I'm so sorry I could find  the link right now) that uses this approach for locking:</p>
  
  <pre><code>var current = Thread.CurrentThread.ManagedThreadId;
  while (Interlocked.CompareExchange(ref owner, current, 0) != current) { }
  
  // PROCESS SOMETHING HERE
  
  if (current != Interlocked.Exchange(ref owner, 0))
          throw new UnauthorizedAccessException("Thread had access to cache even though it shouldn't have.");
  </code></pre>
  
  <p>Instead of the traditional <code>lock</code>:</p>
  
  <pre><code>lock(lockObject)
  {
      // PROCESS SOMETHING HERE
  }
  </code></pre>
  
  <p>The question is: Is there any real reason for doing this? Is it faster or have some hidden benefit?</p>
  
  <p>PS: I know there's a <code>ConcurrentDictionary</code> in some latest version of .NET but I can't use for a legacy project.</p>
  
  <p><strong>Edit</strong>:</p>
  
  <p>In my specific case, what I'm doing is just manipulating an internal <code>Dictionary</code> class in such a way that it's thread safe.</p>
  
  <p>Example:</p>
  
  <pre><code>public bool RemoveItem(TKey key)
  {
      // open lock
      var current = Thread.CurrentThread.ManagedThreadId;
      while (Interlocked.CompareExchange(ref owner, current, 0) != current) { }
  
  
      // real processing starts here (entries is a regular `Dictionary` class.
      var found = entries.Remove(key);
  
  
      // verify lock
      if (current != Interlocked.Exchange(ref owner, 0))
          throw new UnauthorizedAccessException("Thread had access to cache even though it shouldn't have.");
      return found;
  }
  </code></pre>
  
  <p>As @doctorlove suggested, this is the code: <a href="https://github.com/miensol/SimpleConfigSections/blob/master/SimpleConfigSections/Cache.cs" rel="noreferrer">https://github.com/miensol/SimpleConfigSections/blob/master/SimpleConfigSections/Cache.cs</a></p>