ReaderWriterLock Reborn

October 19, 2007

It turns out the ReaderWriterLock has a few flaws, it’s not that it doesn’t work. It just doesn’t work as well as it should. Microsoft have admitted its not as good as it could be and have provided another Reader-Writer lock implementation in .net 3.5 called ReaderWriterLockSlim.

They have decided not to change the existing ReaderWriterLock for backwards compatibility issues, instead we have two versions. For virtually all use cases we should be switching to the new ReaderWriterLockSlim but there are a few subtle differences which can affect which one we choose.

ReaderWriterLock

  • Is slow, about 6-7x slower than a Monitor.Enter
  • Favors read locks, if you have lots of read lock requests then it can prove difficult for a write to get a lock. Depending on how many of which type of lock gets requested you can end up with a situation where your Write requests are waiting a long time.
  • Upgrading a reader to a writer is not atomic.

Jeff Richter has a great MSDN article about its deficiencies.

ReaderWriterLockSlim

  • Is much quicker, only 2x slower than a Monitor.Enter.
  • Favors writes over reads.
  • Upgrades from reader to writer are atomic.

And the cons, which will determine if we should be using the original.

  • Doesn’t handle ThreadAbort exceptions or Out Of Memory Exceptions very well. Can end up pegging the CPU at 100%. This should not really be much of an issue in practice since we shouldn’t really be forcing aborts that raise thread abort exceptions and out of memory exceptions are extremely difficult to recover from anyway.
  • Not suitable for use in hosted CLR scenarios such as SQL Server, use the original if you want to run your code inside of SQL server.

Leave a comment