I saw this singleton recommendation (with partial code) in the mprss book:
public static Singleton GetSingleton() { if (s_value != null) return s_value; Monitor.Enter(s_lock); if (s_value == null) { Singleton temp = new Singleton(); Interlocked.Exchange(ref s_value, temp); } Monitor.Exit(s_lock); return s_value; }
We add two lines of code in the second block of the if statement, and not just write:
s_value = new Singleton();
this should handle the situation when the second thread enters the method and finds s_value != null but not initialized.
My question is: can we just write on the second if block:
{ Singleton temp = new Singleton(); s_value = temp; // instead of Interlocked.Exchange(ref s_value, temp); }
So now the function:
public static Singleton GetSingleton() { if (s_value != null) return s_value; Monitor.Enter(s_lock); if (s_value == null) { Singleton temp = new Singleton(); s_value = temp; } Monitor.Exit(s_lock); return s_value; }
I think not, because they do not use it.
Does anyone have any suggestions?
Is it possible that an svalue might contain uninitialized ones? The svalue can be built right after temp has been fully initialized (maybe I'm wrong). if I'm wrong, maybe an example point, is that wrong? can the compiler generate other code?
roman source share