C# 锁定实例对象内的对象
我遇到了一种情况,迫使我锁定实例对象内部的锁对象,我想知道这是真的吗?
澄清一下:
public class classA
{
object objLock = new object();
public void MethodA(object objClassA)
{
classA cls = (classA)objClassA;
lock(cls.objLock)
{
Do something with cls
}
}
}
可以这样做吗?
i faced ith situation that force me to lock a lock object that is inside of instance object i want to know is it true or not?
for clarify :
public class classA
{
object objLock = new object();
public void MethodA(object objClassA)
{
classA cls = (classA)objClassA;
lock(cls.objLock)
{
Do something with cls
}
}
}
is it allowed to do it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您锁定的对象位于同一个类中,但属于不同的实例。从这个意义上说,您并没有破坏封装,但您仍然应该更喜欢提取该代码,以便可以防止锁定外部对象。这是一个例子:
The object you lock on is in the same class, but a different instance. In that sense you are not breaking encapsulation, but you should still prefer extracting that code so you can prevent locking on an external object. Here's an example:
这完全没问题。这是合法的 C#。事实上,这是替代锁定this的首选方式。因为 this 可以从类外部锁定,而 objLock 是私有的只能在类内锁定,这可以让您更好地控制并避免一些死锁情况
,但是转换可能会抛出异常一个例外。您可能想要处理这种情况
This is perfectly fine. It is legal C#. In fact this is the preferred way instead of locking this. Because this can be locked from outside the class whereas objLock being private can only be locked within the class, giving you better control and avoiding some deadlock conditions
However the casting could potentially throw an exception. You might want to handle that scenario