Hi today I want to share Thread Safe Singleton code sample.
I found this samples from Here
You can use Singleton_Lazy class if you are using .net framework 4.0+
namespace Patterns
{
public class Singleton
{
private static readonly Singleton instance = new Singleton();
//Empty for laziness
static Singleton() { }
private Singleton() {
Console.WriteLine("CCTOR");
}
public static Singleton Instance { get { return instance; } }
public void DoSomeThing()
{
Console.WriteLine("DoSomeThing");
}
}
public sealed class Singleton_Lazy
{
private static readonly Lazy<Singleton_Lazy> lazy =
new Lazy<Singleton_Lazy>(() => new Singleton_Lazy(),true);
public static Singleton_Lazy Instance { get { return lazy.Value; } }
private Singleton_Lazy()
{
Console.WriteLine("CCTOR");
}
public void DoSomeThing()
{
Console.WriteLine("DoSomeThing");
}
}
}
No comments:
Post a Comment