Is Lazy<T> a good solution for a thread safe lazy loaded singleton?

拟墨画扇 提交于 2019-12-06 19:04:08

问题


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).

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

I.E.

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

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

回答1:


I suggest you to read referencede articles from comments:

  • Lazy Class
  • Implementing the Singleton Pattern in C#

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.



来源:https://stackoverflow.com/questions/30076233/is-lazyt-a-good-solution-for-a-thread-safe-lazy-loaded-singleton

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!