Wednesday, July 2, 2008

Singleton pattern in a multi-threaded C# application

This is piece of code will assure the creation of a single instance of the singleton class in a multi-threaded application and at the same time highly performing

public class Singleton
{
private static Singleton _instance;
private static readonly object syncObject = new object();

public static Singleton instance
{
get
{
if (_instance == null)
{
lock (syncObject)
{
if (_instance == null)
_instance = new Singleton();
}
}
return _instance;
}
}

}