VSTS, Oslo, INETA, ASP.NET, Debugging .NET Applications, Tips and Tricks

April 02, 2005

Singleton pattern using MemoryBarrier

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()...”.


# posted by Martin Kulov @ 4:34 PM

Share |







This page is powered by Blogger. Isn't yours?

 








Recent posts



Locations of visitors to this page



History




 
Copyright © 2004-2008 CodeAttest Ltd. All Rights Reserved.
<%-- Google Analytics code --%> <%-- Google Analytics code --%>