Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

lock(X) vs lock(typeof(X))

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))
{
    ...
}
like image 221
Firedragon Avatar asked Nov 18 '11 15:11

Firedragon


1 Answers

  • 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();
like image 198
sehe Avatar answered Nov 15 '22 18:11

sehe