crazy novice
crazy novice

Reputation: 1817

what object type/instance to use for synchronization

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.

Upvotes: 2

Views: 49

Answers (1)

ken2k
ken2k

Reputation: 48985

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.

Upvotes: 2

Related Questions