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