阅读量:81
在C#中实现线程安全的singleton可以通过以下几种方法:
- 使用双重检查锁定(Double-Checked Locking):
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;
}
}
}
- 使用Lazy
类型:
public sealed class Singleton
{
private static readonly Lazy lazy = new Lazy(() => 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