lock
statement blocks execution of a code block for single thread that hold lock- the same thread can acquire and release lock again
- any other thread is blocked from the statement
- lock on dedicated instance only
- using the same instance on multiple
lock
statements may lead to deadlock - avoid using as lock
this
, as it might be used by the callers as a lock- Type instances, as those might be obtained by the typeof operator or reflection
- string instances, including string literals, as those might be interned
- Hold a lock for as short time as possible to reduce lock contention.
Below code block is translated by compiler
lock (x)
{
// Your code...
}
to:
object __lockObj = x;
bool __lockWasTaken = false;
try
{
System.Threading.Monitor.Enter(__lockObj, ref __lockWasTaken);
// Your code...
}
finally
{
if (__lockWasTaken) System.Threading.Monitor.Exit(__lockObj);
}
Further read:
https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/statements/lock