Essential C# Lock Statement  Suggest an edit

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.

Table Of Contents
22 Enum
25 GUID
107 Stream
108 Timers
117 Lock Statement
  ↑ ↓ to navigate     ↵ to select     Esc to close