是懒惰的吗?线程安全的延迟加载单例的好解决方案?
我们使用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.