0
0
CsharpConceptBeginner · 4 min read

What is ReaderWriterLock in C#: Explanation and Example

ReaderWriterLock in C# is a synchronization tool that allows multiple threads to read data simultaneously while only one thread can write at a time. It helps improve performance by letting many readers access shared data concurrently but ensures exclusive access for writers to avoid conflicts.
⚙️

How It Works

Imagine a library where many people can read books at the same time, but only one person can write or edit a book at once. ReaderWriterLock works similarly for computer programs. It lets many threads read shared data at the same time without waiting, which speeds things up.

However, when a thread needs to change (write) the data, it must wait until all readers finish and block new readers until it finishes writing. This prevents data from getting mixed up or corrupted. So, it balances allowing many readers with safe, exclusive writing.

💻

Example

This example shows how to use ReaderWriterLock to protect a shared integer. Multiple threads can read the value at the same time, but only one can write it exclusively.

csharp
using System;
using System.Threading;

class Program
{
    static ReaderWriterLock rwLock = new ReaderWriterLock();
    static int sharedData = 0;

    static void Main()
    {
        Thread writer = new Thread(WriteData);
        Thread reader1 = new Thread(ReadData);
        Thread reader2 = new Thread(ReadData);

        reader1.Start();
        reader2.Start();
        writer.Start();

        reader1.Join();
        reader2.Join();
        writer.Join();
    }

    static void WriteData()
    {
        rwLock.AcquireWriterLock(Timeout.Infinite);
        try
        {
            Console.WriteLine("Writer: Writing data...");
            sharedData = 42;
            Thread.Sleep(500); // Simulate work
            Console.WriteLine("Writer: Data written.");
        }
        finally
        {
            rwLock.ReleaseWriterLock();
        }
    }

    static void ReadData()
    {
        rwLock.AcquireReaderLock(Timeout.Infinite);
        try
        {
            Console.WriteLine($"Reader {Thread.CurrentThread.ManagedThreadId}: Reading data = {sharedData}");
            Thread.Sleep(200); // Simulate work
        }
        finally
        {
            rwLock.ReleaseReaderLock();
        }
    }
}
Output
Reader 4: Reading data = 0 Reader 5: Reading data = 0 Writer: Writing data... Writer: Data written.
🎯

When to Use

Use ReaderWriterLock when you have data that many threads read often but write to rarely. It helps your program run faster by letting many readers access data at the same time without waiting.

For example, in a web server, many users might read the same configuration data, but only an admin occasionally updates it. Using ReaderWriterLock lets all users read quickly while keeping updates safe.

Key Points

  • Multiple readers can access data simultaneously.
  • Only one writer can modify data at a time.
  • Writers block readers and other writers until done.
  • Improves performance when reads are frequent and writes are rare.
  • Use carefully to avoid deadlocks and ensure locks are released.

Key Takeaways

ReaderWriterLock allows multiple threads to read shared data simultaneously but only one to write at a time.
It improves performance when reads happen more often than writes by reducing waiting time for readers.
Always release locks properly to avoid deadlocks and ensure program stability.
Use ReaderWriterLock in scenarios with frequent reads and infrequent writes to shared resources.