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;
}
}

}

1 comment:

Siby T P said...

Dear,


Thanks for your post.

if instance is null, you are locking the instance, but what will happen if instance is not null.


I think it is not locking.