在C#中實(shí)現(xiàn)線程安全的singleton可以通過(guò)以下幾種方法:
public sealed class Singleton
{
private static Singleton instance;
private static readonly object lockObject = new object();
private Singleton() { }
public static Singleton Instance
{
get
{
if (instance == null)
{
lock (lockObject)
{
if (instance == null)
{
instance = new Singleton();
}
}
}
return instance;
}
}
}
public sealed class Singleton
{
private static readonly Lazy<Singleton> lazy = new Lazy<Singleton>(() => new Singleton());
public static Singleton Instance { get { return lazy.Value; } }
private Singleton() { }
}
public sealed class Singleton
{
private static readonly Singleton instance = new Singleton();
static Singleton() { }
private Singleton() { }
public static Singleton Instance
{
get
{
return instance;
}
}
}
以上三種方法都可以確保在多線程環(huán)境下創(chuàng)建唯一的實(shí)例并保證線程安全性。其中,雙重檢查鎖定是一種常用的方式,Lazy