2

I have seen different variations of objects used when acquiring a lock

  1. A static private object

    public class MyClass
    {
      private static object syncBlock = new object();
    
      private void MyMethod()
      {
          lock (syncBlock)
          {
    
          }
      }
    

    }

  2. A class level private object

    public class MyClass
    {
       private object syncBlock = new object();
    
       private void MyMethod()
       {
           lock (syncBlock)
           {
    
           }
       }
    }
    
  3. using the type itself

    public class MyClass
    {
       private void MyMethod()
       {
           lock (typeof (MyClass))
           {
    
           }
       }
    }
    
  4. using this:

    public class MyClass
    {
       private void MyMethod()
       {
          lock (this)
          {
    
          }
       }
    }
    

Can someone elaborate what are the pro/cons of each of these and if one should be preferred over others in a given scenario.

Yuval Itzchakov
  • 146,575
  • 32
  • 257
  • 321
crazy novice
  • 1,757
  • 3
  • 14
  • 36

1 Answers1

2

Don't use lock(this).

Don't use lock(typeof(MyClass)) either.

As for static vs instance, it depends on what is appropriate for you. If you use a static private object, then all instances of your class will share the lock. If you use a private object that is not static, then each instance will have its own lock. So there is no pro/cons, it depends on what you need.

Community
  • 1
  • 1
ken2k
  • 48,145
  • 10
  • 116
  • 176
  • Thanks ken2k. The whole idea of locking is to protect data from multiple instances. Based on that shouldn't we always have a static. Can you provide any uses cases where we should not be using static? – crazy novice Jun 24 '14 at 13:38
  • 1
    @PaulSnow When you want to modify instance fields/properties of the type. – Yuval Itzchakov Jun 24 '14 at 13:44