In this blog I want to describe you three ways how to write singleton class that is thread safe.
First Class
public
sealed class TSSingleton
{
private static volatile TSSingleton instance = null;
private static object syncObj = new object();
// make the default constructor private,
// so that no can directly create it.
private TSSingleton(){}
// public property that can only get
// the single instance of this class.
public static TSSingleton Instance
{
get {
// only create a new instance if one doesn't already exist.
if (instance == null)
{
// use this lock to ensure that only one thread is access
// this block of code at once.
lock(syncObj)
{
if (instance == null)
instance = new TSSingleton();
}
}
// return instance where it was just
// created or already existed.
return instance;
}}}
Second Class
sealed class MysingleTon
{
// Static members are lazily initialized.
// .NET guarantees thread safety for static initialization
private static readonly MysingleTon instance = new MysingleTon();
public static MysingleTon GetInstance()
{
return instance;
}
}
Thrid Class
sealed class Singleton
{
private Singleton() { }
public static readonly Singleton TheInstance = new Singleton();
}
I use last example of singleton class.