Using the lock
statement you can control different threads' access to code within the code block. It is commonly used to prevent race conditions, for example multiple threads reading and removing items from a collection. As locking forces threads to wait for other threads to exit a code block it can cause delays that could be solved with other synchronization methods.
MSDN
The lock keyword marks a statement block as a critical section by obtaining the mutual-exclusion lock for a given object, executing a statement, and then releasing the lock.
The lock keyword ensures that one thread does not enter a critical section of code while another thread is in the critical section. If another thread tries to enter a locked code, it will wait, block, until the object is released.
Best practice is to define a private object to lock on, or a private static object variable to protect data common to all instances.
In C# 5.0 and later, the lock
statement is equivalent to:
bool lockTaken = false;
try
{
System.Threading.Monitor.Enter(refObject, ref lockTaken);
// code
}
finally
{
if (lockTaken)
System.Threading.Monitor.Exit(refObject);
}
For C# 4.0 and earlier, the lock
statement is equivalent to:
System.Threading.Monitor.Enter(refObject);
try
{
// code
}
finally
{
System.Threading.Monitor.Exit(refObject);
}