CodeGo.net>锁定字段或局部变量?

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

有时我看到有人锁定局部变量.

该代码是否损坏?

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

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

由于每个线程都获取o的新实例,因此将有多个锁.

我在这里想念什么?在这种特定情况下,它不应该锁定字段吗?

最佳答案

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.

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