title: Replacing ReaderWriterLock with ReaderWriterLockSLim - troubles
body: <p>Due to performance problems, I have replaced <a href="http://msdn.microsoft.com/en-us/library/system.threading.readerwriterlock.aspx" rel="nofollow noreferrer"><code>ReaderWriterLock</code></a> with <a href="http://msdn.microsoft.com/en-us/library/system.threading.readerwriterlockslim.aspx" rel="nofollow noreferrer"><code>ReaderWriterLockSlim</code></a>. I am experiencing troubles, caused by code that functioned correctly when it was using a RWL.</p>
  
  <p>As you can see, sometimes <code>MethodA</code> (which acquires a <em>write</em> lock) calls another method (which acquires a <em>read</em> lock). The second method is also called from different places, so not always there is lock collision. Previously, AcquiringRead lock doesn't cause that problem. </p>
  
  <p>Is there any solution except from placing "if IsRWheld"?</p>
  
  <p>The problem is something like that:</p>
  
  <pre><code>class Avacado
  {
     ReaderWriterLockSlim _lock = new ReaderWriterLockSlim();
  
     void MethodA()
     {
        _lock.TryEnterWriteLock(-1);
           LockedList.Add(someItem)
           var result = MethodX();
        _lock.ExitWriteLock();
     }
  
     object MethodX()
     {
        //if called from MethodA, it will throw an exception
        _lock.TryEnterReadLock(-1);
  
        //...some stuff with LockedList...
        var result = LockList.Something();
  
        _lock.ExitReadLock();
  
        return result;
     }
  }
  </code></pre>