简体   繁体   English

延迟初始化

[英]Lazy initialization

I am wondering what is the difference between two constructor overloads of Lazy<T> class. 我想知道Lazy<T>类的两个构造函数重载之间有什么区别。

Lazy(Func, Boolean) - Initializes a new instance of the Lazy class. Lazy(Func,Boolean)-初始化Lazy类的新实例。 When lazy initialization occurs, the specified initialization function and initialization mode are used. 发生延迟初始化时,将使用指定的初始化函数和初始化模式。

Lazy(Func, LazyThreadSafetyMode) - Initializes a new instance of the Lazy class that uses the specified initialization function and thread-safety mode. Lazy(Func,LazyThreadSafetyMode)-初始化Lazy类的新实例,该实例使用指定的初始化函数和线程安全模式。

Is the second constructor more flexible from the point of thread-safety? 从线程安全的角度来看,第二个构造函数是否更灵活? Which LazyThreadSafetyMode member is an analogue for Lazy<...>(..., true) ? 哪个LazyThreadSafetyMode成员是Lazy<...>(..., true)的类似物?

From Reflector: 从反射器:

public Lazy(Func<T> valueFactory, bool isThreadSafe) : this(valueFactory, isThreadSafe ?LazyThreadSafetyMode.ExecutionAndPublication : LazyThreadSafetyMode.None)
{
}

So if you pass true it will convert to LazyThreadSafetyMode.ExecutionAndPublication . 因此,如果传递true ,它将转换为LazyThreadSafetyMode.ExecutionAndPublication

false will convert to LazyThreadSafetyMode.None false将转换为LazyThreadSafetyMode.None

By the way, if you only pass the value factor (omitting the bool altogether), it uses LazyThreadSafetyMode.ExecutionAndPublication . 顺便说一句,如果仅传递值因子(完全省略布尔值),它将使用LazyThreadSafetyMode.ExecutionAndPublication

If you pass true the object is initialized with the ExecutionAndPublication lazy mode. 如果您通过true ,则使用ExecutionAndPublication惰性模式初始化该对象。 If you pass false the object is initialized with the None mode. 如果传递false ,则使用None模式初始化该对象。

If you use an overload that does not take a boolean it is initialized with the ExecutionAndPublication mode. 如果使用不带布尔值的重载,则会使用ExecutionAndPublication模式对其进行初始化。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM