gpt4 book ai didi

c# - 当 Lazy 的 .value 属性未锁定时,它如何提供线程安全的延迟加载?

转载 作者:行者123 更新时间:2023-11-30 14:07:48 24 4
gpt4 key购买 nike

<分区>

好的,所以我一直在查看 source code for Lazy<T>因为我想扩展它。我知道从理论上讲,它应该是线程安全的,但我不知道它是如何实现的。看起来它是 .value getter,它在读取值之前不会锁定任何东西。

public T Value
{
get
{
Boxed boxed = null;
if (m_boxed != null )
{
// Do a quick check up front for the fast path.
boxed = m_boxed as Boxed;
if (boxed != null)
{
return boxed.m_value;
}
LazyInternalExceptionHolder exc = m_boxed as LazyInternalExceptionHolder;
Contract.Assert(m_boxed != null);
exc.m_edi.Throw();
}

// Fall through to the slow path.
#if !FEATURE_CORECLR
// We call NOCTD to abort attempts by the debugger to funceval this property (e.g. on mouseover)
// (the debugger proxy is the correct way to look at state/value of this object)
Debugger.NotifyOfCrossThreadDependency();
#endif
return LazyInitValue();

}
}

据我了解,为了线程安全,在写入和读取时都必须锁定某些东西,因为如果读取被写入中断,它可能会返回不正确的数据,甚至出现错误。这种理解是正确的,还是 Lazy 发生了一些复杂的事情?

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com