C# 他很懒<;T>;一个线程安全的延迟加载单例的好解决方案?
我们使用get上的双重锁定实现了一个延迟加载的单例,以确保实例只初始化一次(而不是由于线程竞争条件而初始化两次) 我想知道简单地使用C# 他很懒<;T>;一个线程安全的延迟加载单例的好解决方案?,c#,multithreading,singleton,C#,Multithreading,Singleton,我们使用get上的双重锁定实现了一个延迟加载的单例,以确保实例只初始化一次(而不是由于线程竞争条件而初始化两次) 我想知道简单地使用Lazy是否是解决这个问题的好方法 即 private static Lazy_instance=new Lazy(()=>return new MyClass()); 公共静态MyClass实例 { 得到 { 返回_instance.Value; } } 我建议您阅读评论中的参考文章: 在所有情况下,Lazy类都是线程安全的,但是您需要记住,这种类型的值可
Lazy
是否是解决这个问题的好方法
即
private static Lazy_instance=new Lazy(()=>return new MyClass());
公共静态MyClass实例
{
得到
{
返回_instance.Value;
}
}
我建议您阅读评论中的参考文章:
Lazy
类都是线程安全的,但是您需要记住,这种类型的值可能是线程不安全的,并且可能在多线程环境中损坏:
private static Lazy<MyClass> _instance = new Lazy<MyClass>(() => return new MyClass());
public static MyClass Instance
{
get {
return _instance.Value;
}
}
public void MyConsumerMethod()
{
lock (Instance)
{
// this is safe usage
Instance.SomeMethod();
}
// this can be unsafe operation
Instance.SomeMethod();
}
private static Lazy_instance=new Lazy(()=>return new MyClass());
公共静态MyClass实例
{
得到{
返回_instance.Value;
}
}
public void MyConsumerMethod()
{
锁(实例)
{
//这是安全使用
SomeMethod();
}
//这可能是不安全的操作
SomeMethod();
}
您也可以根据应用程序的环境使用。当然可以。当然可以。Jon Skit关于这个主题的好文章:
private static Lazy<MyClass> _instance = new Lazy<MyClass>(() => return new MyClass());
public static MyClass Instance
{
get {
return _instance.Value;
}
}
public void MyConsumerMethod()
{
lock (Instance)
{
// this is safe usage
Instance.SomeMethod();
}
// this can be unsafe operation
Instance.SomeMethod();
}