Here is a simple program which explain how do we achieve the thread safe design pattern
public class Singleton
{
// mutex object is used to lock the instance creation to avoid dead lock
private static readonly object mutex = new object();
private static Singleton instance;
private Singleton()
{
// private constructor restricts the outside world from creating the current class object
}
public static Singleton Instance
{
get
{
if (instance == null)
{
lock (mutex)
{
instance = new Singleton();
}
}
return instance;
}
}
public void MyPublicMethod()
{
// Do some action
}
}
And the client method to check whether one object is only created in memory
public void CallSingleton()
{
Singleton singleton = Singleton.Instance;
Singleton singletonObjectToCompare = Singleton.Instance;
if (singleton == singletonObjectToCompare)
{
Console.WriteLine("wow same");
}
}
public class Singleton
{
// mutex object is used to lock the instance creation to avoid dead lock
private static readonly object mutex = new object();
private static Singleton instance;
private Singleton()
{
// private constructor restricts the outside world from creating the current class object
}
public static Singleton Instance
{
get
{
if (instance == null)
{
lock (mutex)
{
instance = new Singleton();
}
}
return instance;
}
}
public void MyPublicMethod()
{
// Do some action
}
}
And the client method to check whether one object is only created in memory
public void CallSingleton()
{
Singleton singleton = Singleton.Instance;
Singleton singletonObjectToCompare = Singleton.Instance;
if (singleton == singletonObjectToCompare)
{
Console.WriteLine("wow same");
}
}