是使用现有的对象,而不是创建一个特定的锁对象安全吗? [英] Is using an existing object rather than creating a specific lock object safe?

查看:260
本文介绍了是使用现有的对象,而不是创建一个特定的锁对象安全吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

编辑:事实证明,当我在浏览我发现了一个问题似乎是和我一样,我没有发现更早版本:的锁(柜)和锁之间的差异(variable_which_I_am_using)

As it turns out when I was browsing I found a question the appears to be the same as mine which I didn't find earlier: Difference between lock(locker) and lock(variable_which_I_am_using)

我在看一些代码,并试图让我的头周围的锁事,我到达那里,我认为。

I am looking at some code and trying to get my head around the locking thing and I am getting there I think.

现在我在一些代码我检讨,对象发现是像这样创建:

Now I noticed in some code I am reviewing that an object is created like so:

private HashSet<Graphic> clustersInUse = new HashSet<Graphic>();



然后再在代码中使用像这样:

Then further in the code is used like so:

lock (clustersInUse)
{
   // Do something with the Hashset
}

现在,有没有问题,这样做,而不是创造了锁的特定对象。像这样的:

Now, is there a problem doing this rather than creating a specific object for the lock. Like this:

private object clusterLocker = new object();



会发生什么,如果 clustersInUse 上面莫名其妙地得到放到一个公共财产,那么会发生什么?

What happens if the clustersInUse above somehow gets put into a public property, what happens then?

另外,如果一些试图访问 clustersInUse 无锁定它虽然它已被锁定在另一个​​线程然后会发生什么呢?

Also, if something tries to access the clustersInUse without locking it whilst it is locked in another thread what would happen then?

推荐答案

您已经差不多回答了自己的问题。对于锁定,这是一般都比较好,专门创建一个对象为目的,通常私下通过表达处于较高水平同步逻辑访问方法使用举行。

You've pretty much answered your own question. For locking, it's generally better to create an object specifically for the purpose, and usually held privately for use by accessor methods that express synchronisation logic at a high level.

这篇关于是使用现有的对象,而不是创建一个特定的锁对象安全吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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