Multithreaded programming requires extra care to ensure threads are accessing data in a safe way. Oana at Programming Tidbits helps us to further understand good and bad locking patterns for multithreaded programming.
The MSDN documentation for lock statement tells us to avoid locking on a public type, or instances beyond your code's control. The common constructs lock (this), lock (typeof (MyType)), and lock ("myLock") violate this guideline:
- lock (this) is a problem if the instance can be accessed publicly.
- lock (typeof (MyType)) is a problem if MyType is publicly accessible.
- lock(“myLock”) is a problem since any other code in the process using the same string, will share the same lock.
Best practice is to define a private object to lock on, or a private static object variable to protect data common to all instances.
As a general rule, it's bad to lock an object you didn't create and don't know who else might be accessing. Doing so invites deadlocks and hard to debug issues. As the msdn documentation suggests, the best practice is to only lock private objects.
View the entire article on her blog Programming Tidbits.