锁(此) [英] Lock(This)

查看:87
本文介绍了锁(此)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,

我读了锁的概念,发现锁(此)或锁(公共类型)有问题.
这样做的问题是什么?

请举例说明

Hello All ,

I was readinf the lock concept and find that there is problem with lock(this) or lock(public type).
what is the problem doing like that ?

Please explain me with an example

推荐答案

研究的一个很好的起点是
A good starting point for research is the documentation[^]. I think you would be surprised at the information available in MSDN.


Lock(this)和Lock(type)的问题在于这些对象是公共的,因此外部代码可以锁定它们.因此,如果您的类名为YourClass,我可以编写如下代码:

The problem with Lock(this) and Lock(type) is that these objects are public, so an external code could lock on them. So if your class is named YourClass, I can make a code like this:

YourClass obj = new YourClass();<br />lock(obj){ ... }<br />




这很可能会使您的内部代码陷入僵局.公共类型也有同样的问题.既然锁定要保护的对象是很常见的事,那么像这样的代码就很难发生.

最好的方法是创建一个仅用于锁定它的对象.锁定类对象.使此锁定对象为静态",您将获得锁定类型的相同效果.




And that would probably deadlock your internal code. Same problem for a public type. Since it is commom to lock an object that you want to protect, it''s not too dificult for a code like this to happen.

The best approach is to create an object just for locking on it, instead of locking the class object. Make this locking object "static" and you get the same effect of locking a type.


Leonardo Muzzi提供的答案(此) [^ ]是正确的.

我的建议进一步补充:因此,在某种类型的实例上锁定数据的最通用的简单方法是声明非静态私有锁定对象:

The answer provided by Leonardo Muzzi (this one)[^] is correct.

My advice adds to this: Therefore, most universal simple way to lock data on some type''s instance is to declare non-static private lock object:

private object LockObject = new object();
//...
lock (this.LockObject) {/*...*/}



在某些情况下,数据类的数据的某些部分是完全独立的,因此您不需要在它们之间互锁,而需要锁定每个部分.然后,通过拥有与数据独立部分相同数量的锁定对象来单独进行操作.

最后,到目前为止,lock本身并不构成一般情况.在非常典型的情况下,当您从数据类型实例中读取数据或对其进行写入时,您需要不同的访问权限.特别是,通常有很多读取,而更少写入.在这种情况下,请使用System.Threading.ReaderWriterLockSlim(请参阅有关该主题的Microsoft文档).要定位.NET Framework v.2.0,需要另一种(目前已过时)的类型:System.Threading.ReaderWriterLock,但是性能不佳.



There can be cases when some portions of data your data class are completely independent, so you don''t need to interlock between them, but need to lock each portion. Then, do it separately, by having as many lock objects as the number of those independent portions of data.

Finally, lock construct itself in by far not a the general case. There are very typical cases when you need different access when you read data from your data type instance or you write to it. In particular, it is very usual that there are many reads, much less writes. In this case, use System.Threading.ReaderWriterLockSlim (see Microsoft documentation on the topic). To target .NET Framework v.2.0, another (presently obsolete) type is needed: System.Threading.ReaderWriterLock, but performance is not as good.


这篇关于锁(此)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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