Ron*_*Ron 16 c# singleton multithreading
我们在get上使用双重锁定实现了一个延迟加载的单例,以确保实例仅初始化一次(而不是由于线程竞争条件而导致的两次).
我想知道如果简单地使用Lazy<T>是一个很好的解决方案吗?
IE
private static Lazy<MyClass> _instance = new Lazy<MyClass>(() => return new MyClass());
public static MyClass Instance
{
get
{
return _instance.Value;
}
}
Run Code Online (Sandbox Code Playgroud)
我建议你阅读评论中的referencede文章:
在所有情况下,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();
}
Run Code Online (Sandbox Code Playgroud)
您还可以根据应用程序的环境使用任何您喜欢的构造函数.