对于线程安全的延迟加载单例,Lazy <t>是一个很好的解决方案吗?

时间:2015-05-06 12:06:13

标签: c# multithreading singleton

我们在get上使用双重锁定实现了一个延迟加载的单例,以确保实例仅初始化一次(并且由于线程争用条件而不是两次)。

我想知道简单地使用Lazy<T>是否是解决此问题的好方法?

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

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

1 个答案:

答案 0 :(得分:7)

我建议你阅读评论中的参考文章:

在所有情况下,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();
}

此外,您可以使用any constructor you like,具体取决于您的应用环境。