懒加载的单例模式中,使用Lazy<T>是否是一个好的线程安全解决方案?

27

我们使用双重锁定的懒加载单例模式来确保实例只被初始化一次,而不是因为线程竞争而初始化两次。

我想知道是否仅使用Lazy<T>就可以很好地解决这个问题?

即:

private static Lazy<MyClass> _instance = new Lazy<MyClass>(() => return new MyClass());

public static MyClass Instance
{
    get
    {
        return _instance.Value;
    }
}

4
当然,是的。请查看http://csharpindepth.com/Articles/General/Singleton.aspx。 - Matthew Watson
https://msdn.microsoft.com/en-us/library/dd642331%28v=vs.110%29.aspx - Daniel A. White
3
当然。这是Jon Skit关于单例模式的好文章:http://csharpindepth.com/articles/general/singleton.aspx - mwilczynski
1个回答

18

我建议你阅读评论中引用的文章:

在所有情况下,Lazy<T>类是线程安全的,但需要记住该类型的Value在多线程环境下可能不安全而且可能被破坏:

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();
}

您还可以根据应用程序的环境使用任何构造函数


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接