Reader-Writer Locks

The ReaderWriterLockSlim class enables multiple threads to read a resource concurrently, but requires a thread to wait for an exclusive lock in order to write to the resource.

You might use a ReaderWriterLockSlim in your application to provide cooperative synchronization among threads that access a shared resource. Locks are taken on the ReaderWriterLockSlim itself.

As with any thread synchronization mechanism, you must ensure that no threads bypass the locking that is provided by ReaderWriterLockSlim. One way to ensure this is to design a class that encapsulates the shared resource. This class would provide members that access the private shared resource and that use a private ReaderWriterLockSlim for synchronization. For an example, see the code example for the ReaderWriterLockSlim class. ReaderWriterLockSlim is efficient enough to be used to synchronize individual objects.

Structure your application to minimize the duration of read and write operations. Long write operations affect throughput directly because the write lock is exclusive. Long read operations block waiting writers, and if at least one thread is waiting for write access, threads that request read access will be blocked as well.

Note

The .NET Framework has two reader-writer locks, ReaderWriterLockSlim and ReaderWriterLock. ReaderWriterLockSlim is recommended for all new development. ReaderWriterLockSlim is similar to ReaderWriterLock, but it has simplified rules for recursion and for upgrading and downgrading lock state. ReaderWriterLockSlim avoids many cases of potential deadlock. In addition, the performance of ReaderWriterLockSlim is significantly better than ReaderWriterLock.

See Also

Reference

ReaderWriterLockSlim

ReaderWriterLock

Other Resources

Managed Threading

Threading Objects and Features