Simple usage
suggest changeCommon 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 a 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 a lock-ed block while another thread is running within it, the former will wait for the other 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.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents