C#锁定的对象,在锁块重新分配 [英] C# Locking an object that is reassigned in lock block

查看:141
本文介绍了C#锁定的对象,在锁块重新分配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一类代码:

 私有静态MyObject的_locker =新MyObject来(); 

...

锁(_locker)
{
...
_locker =新MyObject来();

}



它会继续锁定在_locker <? / p>

解决方案

没有,也不会。从C#规范(重点是我的):




形式的lock语句锁(X)
...
其中x是
引用类型的表达式,b $ b相当于正是美元

  System.Threading.Monitor.Enter(X); 
尝试{

}
终于{
System.Threading.Monitor.Exit(X);
}



但x只计算一次




由于 X 不重新评估该锁将被释放。


I have this code in a class:

private static MyObject _locker = new MyObject();

...

lock (_locker)
{
     ...
     _locker = new MyObject();
     ...
}

Will it keep the lock on _locker ?

解决方案

No, it will not. From the C# specification (emphasis is mine):

A lock statement of the form lock (x) ... where x is an expression of a reference-type, is precisely equivalent to

System.Threading.Monitor.Enter(x);
try {
  ...
}
finally {
  System.Threading.Monitor.Exit(x);
}

except that x is only evaluated once.

Since x is not reevaluated the lock will be released.

这篇关于C#锁定的对象,在锁块重新分配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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