Skip to content

Theraot.Threading.ReadWriteLock

Alfonso J. Ramos edited this page Nov 10, 2015 · 1 revision

ReadWriteLock

This class provides a fully reentrant alternative to ReaderWriterLock and ReaderWriterLockSlim that does not require an explicit upgrade mechanism.

The main interface are four methods: EnterRead, EnterWrite, TryEnterRead and TryEnterWrite.

The first two will return an IDisposable that must be disposed by the same thread to exit the lock. These variants will have the thread wait until the lock is available, acquire it and then return.

The Try variantas return bool and give IDisposable via out parameter. These variants will not wait, intead will try to acquire the lock if it is available at the moment of the call.

Regarding the reentrancy, Read to Read, Write to Read and Write to Write will always be granted. But Read to Write is an upgrade... when there are multiple readers it will require to wait until all other readers exit or decided to try to upgrade too. If multiple threads are trying to upgrade, then only one will be granted the upgrade and the others will recieve InvalidOperationException to prevent a deadlock and to avoid breaking the guarantee that no writes will happen as long as you have a read lock.

To avoid getting the InvalidOperationException it is suggested to use TryEnterRead intead of TryEnter when possible. Otherwise it will be appropiate to catch the exception and handle it properly.

The internally the implementation uses ManualResetEventSlim to allow thread to wait until the locks are available.