Search code examples
c#.netconcurrencylockingreaderwriterlockslim

ReaderWriterLockSlim with LockRecursionPolicy.SupportsRecursion vs lock


I am confused about the warning for ReaderWriterLockSlim SupportsRecursion

From MSDN

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.

What I don't understand is why do this warning not apply to the built in lock statement which is recursive ?


Solution

  • As explained here, the lock keyword in C# is based on a Monitor object, an exclusive synchronization mechanism. "Exclusive" means that, when the first thread enters the critical section, any subsequent threads are blocked.

    ReaderWriterLockSlim, on the other hand, distinguishes between reader locks and writer locks. They are intended to be used in (and provide improved concurrency in) scenarios where there are many readers but only occasional write updates. Reader/Writer locks are non-exclusive.

    A lock knows which thread it was locked on, so if that thread re-enters the critical section, it just increments a counter and continues.

    A ReaderWriterLockSlim is in a more complicated position. Because it distinguishes between read locks and write locks, and because it is sometimes desirable to lock on a write without creating a race condition, the ReaderWriterLockSlim offers an UpgradableLock that allows you to temporarily enhance the lock for write capabilities without worrying about a race condition caused by a rogue write from another thread coming in while you transition to write mode.

    As you can see, ReaderWriterLockSlim offers a more feature-rich, but also more complex model for synchronization than lock does. Its requirement to declare your intention to use recursion is an admission of this additional complexity.

    Further Reading
    Synchronization Essentials: Locking
    Advanced Threading: Reader/Writer Locks
    Why Lock Recursion is Generally a Bad Idea Anyway