本文介绍了是懒惰的吗?线程安全的延迟加载单例的好解决方案?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

We implemented a lazy loaded singleton using double locking on get to make sure the instance is only initialized once (and not twice due to thread race conditions).

我想知道简单地使用Lazy<T>是否可以解决此问题?

I was wondering if simply using Lazy<T> is a good solution for this problem?

IE.

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

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

推荐答案

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

I suggest you to read referencede articles from comments:

  • Lazy Class
  • Implementing the Singleton Pattern in C#

在所有情况下,Lazy<T>类都是线程安全的,但是您需要记住,这种类型的Value可能是线程不安全的,并且在多线程环境中可能会损坏:

In all cases the Lazy<T> class is thread-safe, but you need to remember that the Value of this type can be thread-unsafe, and can be corrupted in multithreading environment:

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

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

Also you can use any constructor you like depending on the environment of your application.

这篇关于是懒惰的吗?线程安全的延迟加载单例的好解决方案?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-11 18:18