锁定的字段或局部变量? [英] Locking on field or local variable?

查看:222
本文介绍了锁定的字段或局部变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个的问题, <一href="http://stackoverflow.com/questions/13681356/threading-in-c-sharp-value-types-and-reference-types-clarification">got从马克的回答

我有时会看到人锁定在一个的本地的变量。

这是code被打破?

 公共无效DO()
{
 对象o =新的对象();
 锁定(O)
     {
      ...
     }
}
 

我相信对象o =新的对象(); 应的之外的方法作为字段

由于每个线程得到的的新实例0 ,将有多个锁。

这有什么,我在这里丢失?因为我知道它应该在领域锁定(在这种特定情况下)。

解决方案
  

我相信对象o =新的对象();应该是方法作为领域之外。

     

因为每个线程越来越邻的新实例,将有多个锁

     

这有什么,我在这里丢失?因为我知道它应该在领域锁定(在这种特定情况下)。

您的理解是正确的。的code为broken.In此实现即使锁将被激活,它不会提供同步,因为它会在不同的对象。

MSDN锁定C#

  

在一般情况下,避免锁定在一个公开的类型,或者情况超出了你的code的控制。共同构建锁定(本),锁(typeof运算(MyType的)),并锁定(myLock)违反此准则:

     
      
  • 在锁(这)是,如果实例可以公开访问的问题。
  •   
  • 在锁(typeof运算(MyType的))是一个问题,如果MyType的是向公众开放。
  •   
  • 在锁(myLock)是一个问题,因为使用相同字符串的任何其他code的过程中,将共享同一个锁。
  •   
     

最佳做法是定义一个私有对象锁定,或者在一个私有静态对象变量,以保护共同所有实例的数据。

After reading this question , and got an answer from marc

I sometimes see people locking on a local variable .

Is this code is broken ?

public void Do()
{
 object  o  = new Object();
 lock (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).

解决方案

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

Your understanding is correct. The code is broken.In this implementation even though lock will be active, it will not provide synchronization as it will be on different objects.

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

这篇关于锁定的字段或局部变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆