Hello everyone,

As mentioned in this article, why using this or type itself as lock object is bad idea? What means "it potentially offers public scope to the synchronization object"?


I quote the whole paragraph below,

Choosing the Synchronization Object
Any object visible to each of the partaking threads can be used as a synchronizing object, subject to one hard rule: it must be a reference type. Itís also highly recommended that the synchronizing object be privately scoped to the class (i.e. a private instance field) to prevent an unintentional interaction from external code locking the same object. Subject to these rules, the synchronizing object can double as the object it's protecting, such as with the list field below:

class ThreadSafe {
  List <string> list = new List <string>();
  void Test() {
    lock (list) {
      list.Add ("Item 1");
A dedicated field is commonly used (such as locker, in the example prior), because it allows precise control over the scope and granularity of the lock. Using the object or type itself as a synchronization object, i.e.:

lock (this) { ... }

lock (typeof (Widget)) { ... }    // For protecting access to statics
is discouraged because it potentially offers public scope to the synchronization object.

thanks in advance,