Skip to content
Tutorials Center
My learning

Topics

C# Reference ยท Async and Concurrency

The ReaderWriterLockSlim class

Reference for ReaderWriterLockSlim in C#: allow many concurrent readers or one writer, use upgradeable locks, recursion policy and common pitfalls.

ReaderWriterLockSlim is a lock with two modes. Any number of threads can hold the read lock at the same time, but the write lock is exclusive: it waits for the readers to leave and blocks everybody else while held. That helps when data is read far more often than it is changed and the reads take noticeable time.

For short critical sections a plain lock is usually as fast or faster, because a reader/writer lock does more bookkeeping. Measure before choosing it.

C#
var rw = new ReaderWriterLockSlim();
rw.EnterReadLock();
try { /* read shared data */ }
finally { rw.ExitReadLock(); }

Try it

C# Many readers, one writer

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

C# Upgradeable locks and state

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Syntax

C#
public class ReaderWriterLockSlim : IDisposable
{
    public ReaderWriterLockSlim();
    public ReaderWriterLockSlim(LockRecursionPolicy recursionPolicy);

    public void EnterReadLock();
    public bool TryEnterReadLock(int millisecondsTimeout);
    public void ExitReadLock();

    public void EnterWriteLock();
    public bool TryEnterWriteLock(int millisecondsTimeout);
    public void ExitWriteLock();

    public void EnterUpgradeableReadLock();
    public bool TryEnterUpgradeableReadLock(int millisecondsTimeout);
    public void ExitUpgradeableReadLock();

    public bool IsReadLockHeld { get; }
    public bool IsWriteLockHeld { get; }
    public bool IsUpgradeableReadLockHeld { get; }
    public int CurrentReadCount { get; }
    public int WaitingReadCount { get; }
    public int WaitingWriteCount { get; }
}
Name Description
recursionPolicy NoRecursion (default) or SupportsRecursion.
millisecondsTimeout Longest wait in the TryEnter* methods; they return false on timeout.

Returns: the TryEnter* methods return true when the lock was acquired.

Errors: LockRecursionException for a forbidden nested enter, SynchronizationLockException when exiting a lock the thread does not hold, ObjectDisposedException after Dispose.

Usage notes

  • At most one upgradeable reader at a time, but it can coexist with ordinary readers. Upgrading waits until those readers leave. Two threads that both hold read locks and try to write will deadlock, which is why the upgradeable mode exists.
  • No recursion by default. Re-entering the same mode throws LockRecursionException. SupportsRecursion allows it but makes the lock slower and the code harder to reason about; avoid it.
  • Writers can starve readers and vice versa. The class prefers waiting writers over new readers to avoid writer starvation, so a steady stream of writes lowers read throughput.
  • Always exit in finally, and call the matching Exit* method for the mode you entered.
  • Not async-friendly. The lock has owner threads, so you cannot hold it across await. Use immutable snapshots, SemaphoreSlim, or a concurrent collection instead.
  • Dispose it when you own it and no thread can use it any more.
  • Consider alternatives. A ConcurrentDictionary, an immutable collection swapped with Volatile.Write, or FrozenDictionary often removes the need for any lock.