After reading some articles on .NET memory model I understood two things. First you should never rely on MSDN for good multithreading advice. And second – the best way to create a singleton is the following:
public sealed class Singleton
{
private Singleton()
{
}
private static Singleton value;
private static object syncRoot = new Object();
public static Singleton Value
{
get
{
if (Singleton.value == null)
{
lock (syncRoot)
{
if (Singleton.value == null)
{
Singleton newVal = new Singleton();
// Insure all writes used
// to construct new value have been flushed.
System.Threading.Thread.MemoryBarrier();
// publish the new value
Singleton.value = newVal;
}
}
}
return Singleton.value;
}
}
}
A very good article and follow ups you can find in Brad Abrams’s “volatile and MemoryBarrier()…”.