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

前端 未结 5 446
不知归路
不知归路 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:56

    There are two issues here:

    First, don't lock on a null object. It doesn't make sense as how can two objects, both null, be differentiated?

    Second, to safely initialise a variable in a multithreaded environment, use the double-checked locking pattern:

    if (o == null) {
        lock (lockObj) {
            if (o == null) {
                o = new Object();
            }
        }
    }
    

    This will ensure that another thread has not already initialised the object and can be used to implement the Singleton pattern.

提交回复
热议问题