Unsafe Way with Lazy Loading :-
public class Program
{
public static void Main(string[] args)
{
var singletonInstance1 = Task.Run<Singleton>(() => Singleton.Intance());
var singletonInstance2 = Task.Run<Singleton>(() => Singleton.Intance());
}
}
public class Singleton
{
private Singleton()
{ }
private static Singleton _instance;
public static Singleton Intance()
{
if (_instance == null)
return new Singleton();
else
return _instance;
}
}
Thread Safe ways with Eager Loading :-
public class Singleton
{
private Singleton()
{ }
private static Singleton _instance = new Singleton();
public static Singleton Intance()
{
return _instance;
}
}
Thread safe with Lazy loading :-
public class Singleton
{
private Singleton()
{ }
private static Singleton _instance;
public static Singleton Intance()
{
lock (_instance) ;
if (_instance == null)
return new Singleton();
else
return _instance;
}
}