Best Practices For Locking Code From Other Threads RRS feed

  • Question

  • I use the lock (object) syntax regularly when I don't want other threads to access a portion of code, but I must admit I'm usually just making my best guess as far as what exactly to lock.  For example, if I do lock (this), I assume that means that 2 threads from the same instance cannot access the code block at the same time, but that a thread from another instance could access the corresponding block of code in that instance.  Also, for creating Singletons the examples I see (and use) are usually locking what appears to be an arbitrary object variable.  Are there any rules (or articles, blogs, etc.) on best practices with regards to what specific object you should lock in various scenarios?



    Thursday, December 9, 2010 7:42 PM



    Hi CF,


    This doc discussed managed threading Best Practices, you may want to have read:


    • Don't use types as lock objects. That is, avoid code such as lock(typeof(X)) in C# or SyncLock(GetType(X)) in Visual Basic, or the use of Monitor.Enter with Type objects. For a given type, there is only one instance of System.Type per application domain. If the type you take a lock on is public, code other than your own can take locks on it, leading to deadlocks. For additional issues, see Reliability Best Practices.
    • Use caution when locking on instances, for example lock(this) in C# or SyncLock(Me) in Visual Basic. If other code in your application, external to the type, takes a lock on the object, deadlocks could occur.
    • Do ensure that a thread that has entered a monitor always leaves that monitor, even if an exception occurs while the thread is in the monitor. The C# lock statement and the Visual Basic SyncLock statement provide this behavior automatically, employing a finally block to ensure that Monitor.Exit is called. If you cannot ensure that Exit will be called, consider changing your design to use Mutex. A mutex is automatically released when the thread that currently owns it terminates.
    • Consider using methods of the Interlocked class for simple state changes, instead of using the lock statement (SyncLock in Visual Basic). The lock statement is a good general-purpose tool, but the Interlocked class provides better performance for updates that must be atomic. Internally, it executes a single lock prefix if there is no contention. In code reviews, watch for code like that shown in the following examples. In the first example, a state variable is incremented.

    Eric Yang [MSFT]
    MSDN Community Support | Feedback to us
    Get or Request Code Sample from Microsoft
    Please remember to mark the replies as answers if they help and unmark them if they provide no help.

    • Marked as answer by Chicken Foot Monday, December 13, 2010 8:49 PM
    Monday, December 13, 2010 6:54 AM