The new ReaderWriterLockSlim class

Last year, in Improper Use of Exceptions, I mentioned that the ReaderWriterLock.AcquireReaderLock and ReaderWriterLock.AcquireWriterLock methods were improperly written because they throw exceptions when the lock is not available. I mentioned further that whoever designed the ReaderWriterLock should have studied the Monitor class for a more rational API.

Apparently I wasn’t the only one to think that, as .NET 3.5 introduced the ReaderWriterLockSlim class, which has a much more Monitor-like interface. ReaderWriterLockSlim reportedly has much better performance than ReaderWriterLock, as well as much simpler rules for lock recursion and upgrading/downgrading locks. The documentation says that ReaderWriterLockSlim avoids many cases of potential deadlock. All in all, it’s recommended over ReaderWriterLock for all new development.

At the time I wrote my note last year, I was especially disappointed that there was no way to wait indefinitely to acquire a reader or writer lock. It turns out that I was wrong: you can wait indefinitely if you pass Timeout.Infinite as the timeout value to AcquireReaderLock or AcquireWriterLock. It’s documented, but not very well. Rather than stating the valid values in the description of the timeout parameter, the documentation for ReaderWriterLock has a link at the end of the Remarks section says, “For valid time-out values, see ReaderWriterLock.”

I guess I need to follow the advice I read so long ago: “Periodically re-read the documentation for the functions you’re calling.”