18

What is the difference between locking on a type of a class vs locking on the class itself?

For example:

private readonly object xmpp = new object();

lock (xmpp)
{
    ...
}

vs

lock (typeof(Xmpp))
{
    ...
}
Firedragon
  • 3,685
  • 3
  • 35
  • 75

1 Answers1

19
  • lock(x) synchronizes on a different lock for each instance of the type

  • lock(typeof(X)) synchronizes on the same lock for all instances of the type

Always lock on a private lock object:

 public class X
 {
      private readonly Object _lock = new Object();

      // ...
            lock (_lock)
            {
            }

If you must synchronize access to class static members, use the same pattern:

 public class X
 {
      private readonly static Object s_lock = new Object();
sehe
  • 374,641
  • 47
  • 450
  • 633
  • 5
    I would just like to point out WHY you should always use a private lock object... Because only your class and code should have access to that lock object, if you lock something publicly accessible someone else could potentially lock your objects and break your code. This really only applies when writing 3rd party libraries, but it's a good pattern and good habit to get in to everywhere. – Bradley Uffner Nov 18 '11 at 15:56
  • Thanks for the comments both of you. Very helpful in my understanding – Firedragon Nov 18 '11 at 15:57
  • 4
    I would also recommend adding the `readonly` keyword to the locking object, for clarity's sake. Not that you would intentionally assign a value, *but* those bugs are always fun. – Bryan Crosby Nov 18 '11 at 18:27