在C#中实现线程安全的singleton可以通过以下几种方法:
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;
}
}
}
以上三种方法都可以确保在多线程环境下创建唯一的实例并保证线程安全性。其中,双重检查锁定是一种常用的方式,Lazy