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
- 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