1. Why the regular lock might be insufficient?
Let's think: we have some shared resource — for example, a list of clients that we store somewhere in our multithreaded app. Most of the time we're only reading that list — for example, showing data in the UI, building reports, filtering and sorting info. Only occasionally someone adds a new client or removes an old one.
If we use the usual lock, any thread that wants to read must wait while another thread finishes reading or, worse, writing. And if about 99% of operations are reads? We end up unnecessarily slowing down all readers, even though they could run in parallel.
That's where a special lock type comes in handy — the Reader-Writer Lock. The key idea: many threads can read simultaneously, but if someone wants to modify something, they take exclusive access, blocking readers.
2. Theory: what is ReaderWriterLockSlim
Brief about the classes
- ReaderWriterLock — older, slower, can lead to deadlocks. Use only if you need to support .NET Framework 2.0.
- ReaderWriterLockSlim — the fast modern alternative (the keyword Slim means "lean", "lightweight"). This class is optimized for frequent competing read/write operations and is recommended for apps with many threads where reads are much more common than writes.
How it works
ReaderWriterLockSlim implements three lock modes:
- Read Lock: many threads can read at the same time.
- Write Lock: only one thread can modify data, and no one else reads.
- Upgradeable Read Lock: only one thread can hold this lock at a time; it reads but can "upgrade" to a write lock if needed.
Lock compatibility chart
| Reader Thread | Writer Thread | Thread with Upgradeable Read Lock | |
|---|---|---|---|
| Reader | ✅ | ⛔ | ✅/⛔ |
| Writer | ⛔ | ⛔ | ⛔ |
| Upgradeable Read | ✅* | ⛔ | ⛔ |
✅ — allowed
⛔ — blocked
— only if the upgradeable read lock hasn't been "upgraded" to write
When to (and when not to) use ReaderWriterLockSlim
Recommended:
- Many concurrent threads that mostly read shared data (reference data, cache, configurations).
- Writes happen rarely (for example, once per second/minute/hour).
- You need to maximize read performance without blocking threads.
Not recommended:
- Reads/writes happen in roughly equal proportions (better to use the regular lock).
- Data changes frequently (the gain is small).
3. Using ReaderWriterLockSlim in practice
Let's extend our sample app! Earlier we built a simple client directory and experimented with multithreaded access to a collection. Now let's complicate things: suppose we have a list of clients that several threads access (for example, a service notifies all clients about a new promo, and another thread adds new clients).
First, describe our client collection:
// The Client class — a familiar hero from previous lectures
public class Client
{
public int Id { get; set; }
public string Name { get; set; }
}
Now create a wrapper for thread-safe access using ReaderWriterLockSlim:
using System;
using System.Collections.Generic;
using System.Threading;
public class ClientDirectory
{
private readonly List<Client> _clients = new List<Client>();
// Slim-lock for read/write
private readonly ReaderWriterLockSlim _lock = new ReaderWriterLockSlim();
// Adding a client (write lock)
public void AddClient(Client client)
{
_lock.EnterWriteLock(); // Only one thread can add a client
try
{
_clients.Add(client);
Console.WriteLine($"[Thread {Thread.CurrentThread.ManagedThreadId}] Client added {client.Name}");
}
finally
{
_lock.ExitWriteLock();
}
}
// Getting a copy of the client list (read lock)
public List<Client> GetClients()
{
_lock.EnterReadLock(); // Many threads can read at the same time
try
{
// Return a copy so someone doesn't accidentally modify the original
return new List<Client>(_clients);
}
finally
{
_lock.ExitReadLock();
}
}
}
4. Multithreaded reading and periodic writing
Suppose there are 5 threads that periodically read all clients ("build reports" or just check who's there), and separately a thread that sometimes adds a new client.
using System.Threading;
class Program
{
static void Main()
{
var directory = new ClientDirectory();
// Thread to add clients
var writerThread = new Thread(() =>
{
for (int i = 1; i <= 5; i++)
{
directory.AddClient(new Client { Id = i, Name = $"Client {i}" });
Thread.Sleep(700); // Simulate long operations
}
});
// Several readers
for (int j = 0; j < 5; j++)
{
int readerId = j + 1;
new Thread(() =>
{
for (int k = 0; k < 10; k++)
{
var clients = directory.GetClients();
Console.WriteLine($"[Reader {readerId}][Thread {Thread.CurrentThread.ManagedThreadId}] Total clients: {clients.Count}");
Thread.Sleep(200); // Read more often than write
}
}).Start();
}
writerThread.Start();
writerThread.Join();
// Give readers time to finish:
Thread.Sleep(3000);
}
}
Almost always several threads can read the client list at the same time (without waiting for each other), but when a thread adds a client — other threads must wait until the write completes. This allows serving many clients without unnecessary reader blocking.
5. Upgradeable lock: UpgradeableReadLock
Sometimes it happens that a thread reads data and only occasionally, if a condition is met, wants to modify it. You might think it's enough to get a read lock, check the condition, then release the read lock and acquire the write lock. But in the time "between" another thread could have changed the data! Enter the upgradeable lock.
Using it is simple:
public bool AddClientIfNotExists(string name)
{
_lock.EnterUpgradeableReadLock(); // Only one thread can hold this lock
try
{
bool exists = _clients.Exists(c => c.Name == name);
if (!exists)
{
_lock.EnterWriteLock(); // Upgrade to write lock
try
{
_clients.Add(new Client { Name = name });
return true;
}
finally
{
_lock.ExitWriteLock();
}
}
return false;
}
finally
{
_lock.ExitUpgradeableReadLock();
}
}
First the thread reads, and if it needs to change — it upgrades the lock level without releasing the list to other threads.
6. Useful nuances
Comparison: ReaderWriterLockSlim vs lock
|
|
|
|---|---|---|
| Concurrent reading | No | Yes |
| Concurrent writing | No | No |
| Support for upgradeable read | No | Yes (EnterUpgradeableReadLock) |
| Speed | Very fast | Faster with frequent reads |
| Memory | Minimal | A bit more |
| Simplicity | Easy | More complex, has nuances |
What it looks like in real projects
In large applications where there are huge tables or caches read by hundreds of threads but changed rarely, using ReaderWriterLockSlim is a way to avoid read "contention". For example:
- Configuration cache used by microservices.
- Reference data storage for financial calculations.
- Internal cache for message routing.
Emphasize — in most cases, especially if you're just starting with multithreading, the regular lock is simpler and safer. ReaderWriterLockSlim is for scenarios where there truly is heavy concurrent reading.
Visualization: access diagram
flowchart TD
A[Reader Thread 1] --Read--> D[ReaderWriterLockSlim]
B[Reader Thread 2] --Read--> D
C[Writer Thread] --Write--> D
D --Read allowed--> E[Reading the shared collection]
D --Write blocks read/write--> F[Writing the shared collection]
While only reads occur — access is open to all; when a write is attempted — everyone waits until the write finishes.
7. ReaderWriterLockSlim: nuances and common mistakes
Lock Recursion: By default ReaderWriterLockSlim does not allow the same thread to re-enter the same type of lock. That is, if a thread already holds a read lock and tries to get it a second time — an exception will be thrown. Same for write lock. However, UpgradeableReadLock can be upgraded to a write lock from inside.
Do not mix up the order: Acquire EnterUpgradeableReadLock() → inside it EnterWriteLock(). But not the other way around!
Exceptions: If you don't release a lock (for example, don't call ExitWriteLock()), other threads will wait forever. So always use try { ... } finally { ... } constructs.
Don't hold it for long: Don't perform long IO operations inside a lock. The longer a thread holds a lock, the more delay for others. Try to exit lock blocks as quickly as possible.
Evaluate complexity: Don't use ReaderWriterLockSlim to protect "tiny" operations where the regular lock is simpler and faster.
GO TO FULL VERSION