Why doesn't C# allow a null value to be locked?

前端 未结 5 480
不知归路
不知归路 2021-01-17 09:27

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 c

5条回答
  •  难免孤独
    2021-01-17 09:51

    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 ...;
                }
            }
        }
    }
    

    Also be careful to avoid this interesting race condition with double-checked locking: Memory Model Guarantees in Double-checked Locking

提交回复
热议问题