Search code examples
c#multithreadinglocking

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


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?


Solution

  • 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