为什么不C#允许空值被锁定? [英] Why doesn't C# allow a null value to be locked?
本文介绍了为什么不C#允许空值被锁定?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
C#不允许锁定在一个空值。我想我可以检查值是否为空或不是我锁定它之前,但因为我还没有锁定它的另一个线程可以一起去,使null值!我怎样才能避免这种竞争状态?
C# doesn't allow locking on a null value. I suppose I could check whether the value is null or not before I lock it, but because I haven't locked it another thread could come along and make the value null! How can I avoid this race condition?
推荐答案
锁定上是从来没有空,如:
Lock on a value that is never null, e.g.
Object _lockOnMe = new Object();
Object _iMightBeNull;
public void DoSomeKungFu() {
if (_iMightBeNull == null) {
lock (_lockOnMe) {
if (_iMightBeNull == null) {
_iMightBeNull = ... whatever ...;
}
}
}
}
另外要小心,以避免双重检查锁定这个有趣的比赛状态:在双重检查锁定
这篇关于为什么不C#允许空值被锁定?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文