1

I've noticed in virtually all examples I've seen that locks on instances are used as follows

public class Foo {
   readonly object locker = new Object();
   public void DoSomething() {
      lock(locker) {
         //...
      }
   }
   public void DoSomethingElse() {
      lock(locker) {
         //...
      }
   }
}

This is very useful when multiple threads might have access to the same instance and you want its methods to be atomic relative to each other.

In my experiments, it would work just as well however if I did a lock(this) rather than having the locker object. Is there something I'm missing or is that perfectly fine?

George Mauer
  • 117,483
  • 131
  • 382
  • 612

1 Answers1

1

The problem is that you don't have exclusive control over this. Other types could lock on your object as well and create havoc.

Microsoft has something to say about this on their page about the lock statement.

In general, 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 because 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.

itsme86
  • 19,266
  • 4
  • 41
  • 57