C# Language Simple usage


Common usage of lock is a critical section.

In the following example ReserveRoom is supposed to be called from different threads. Synchronization with lock is the simplest way to prevent race condition here. Method body is surrounded with lock which ensures that two or more threads cannot execute it simultaneously.

public class Hotel
    private readonly object _roomLock = new object();

    public void ReserveRoom(int roomNumber)
        // lock keyword ensures that only one thread executes critical section at once
        // in this case, reserves a hotel room of given number
        // preventing double bookings
        lock (_roomLock)
            // reserve room logic goes here

If a thread reaches lock-ed block while another thread is running within it, the former will wait another to exit the block.

Best practice is to define a private object to lock on, or a private static object variable to protect data common to all instances.