Locking in .NET

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


object __lockObj = x;
bool __lockWasTaken = false;
    System.Threading.Monitor.Enter(__lockObj, ref __lockWasTaken);
    // Your code...
    if (__lockWasTaken) System.Threading.Monitor.Exit(__lockObj);

Further read:


Leave a Reply

Your email address will not be published. Required fields are marked *

Solve : *
16 + 8 =