CodeAttest
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




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

 




Calendar Martin Kulov's Calendar   RSS Aggregate this blog

DevReach - The Premier Conference for Microsoft Technologies for SEE

Mobility Day 2008 Conference

DevReach - The Premier Conference for Microsoft Technologies in Bulgaria

International Association of Software Architects

SofiaDev .NET User Group

Microsoft Most Valuable Professional

View Martin Kulov's profile on LinkedIn

MSDN Event Bloggers




Recent posts




History




 
Copyright © 2004-2008 CodeAttest Ltd. All Rights Reserved.