在我从Marc阅读this的问题和an answer的问题后…



public void Do()
 object  o  = new Object();
 lock (o)

我相信对象o = new Object();应该在方法之外作为字段.




I believe object o = new Object(); should be outside the method as a Field.

Since each thread is getting a new instance of o , there will be multiple locks.

Is there anything I’m missing here? cause I know it should lock on fields(in this specific case).


MSDN-lock c#

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 since 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.

转载注明原文>锁定字段或局部变量? - 代码日志