Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replacing ReaderWriterLock with ReaderWriterLockSLim - troubles

Due to performance problems, I have replaced ReaderWriterLock with ReaderWriterLockSlim. I am experiencing troubles, caused by code that functioned correctly when it was using a RWL.

As you can see, sometimes MethodA (which acquires a write lock) calls another method (which acquires a read 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.

Is there any solution except from placing "if IsRWheld"?

The problem is something like that:

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;
   }
}
like image 465
Thomas Avatar asked Nov 08 '09 11:11

Thomas


2 Answers

The call to MethodX from MethodA qualifies it as recursive use of the lock.
See the remarks on the MSDN page for ReaderWriterLockSlim :

By default, new instances of ReaderWriterLockSlim are created with the LockRecursionPolicy.NoRecursion flag and do not allow recursion. This default policy is recommended for all new development, because recursion introduces unnecessary complications and makes your code more prone to deadlocks. To simplify migration from existing projects that use Monitor or ReaderWriterLock, you can use the LockRecursionPolicy.SupportsRecursion flag to create instances of ReaderWriterLockSlim that allow recursion.

like image 194
Henk Holterman Avatar answered Sep 20 '22 15:09

Henk Holterman


Another point to consider when replacing ReaderWriterLock by ReaderWriterLockSlim is that the latter implements IDisposable.

This can make the replacement complex - as any types that own a ReaderWriterLockSlim must also be IDisposable.

like image 31
Joe Avatar answered Sep 19 '22 15:09

Joe