LazyInitializer.EnsureInitialized是否有效?有线程安全的明确承诺吗?
我想创建一个可以通过属性注入进行测试的惰性属性。如果我要使用惰性字段,我不知道如何在测试期间注入自己的字段。这是我的代码:
private IExpensive expensive;
private bool expensiveInitialized;
private object expensiveLockingObject = new object();
public IExpensive Expensive
{
get
{
LazyInitializer.EnsureInitialized(ref expensive, ref expensiveInitialized, ref expensiveLockingObject,
() => new Expensive(myStaticArg1, myStaticArg2, ...));
return expensive;
}
internal protected set
{
expensiveInitialized = true;
expensive = value;
}
}
我想知道 BCL 团队是否承诺此代码是线程安全的? 文档尚不清楚。
I'd like to make a Lazy property that can be tested with property injection. If I were to use a Lazy field, I don't see how I would be able to inject my own during testing. Here's my code:
private IExpensive expensive;
private bool expensiveInitialized;
private object expensiveLockingObject = new object();
public IExpensive Expensive
{
get
{
LazyInitializer.EnsureInitialized(ref expensive, ref expensiveInitialized, ref expensiveLockingObject,
() => new Expensive(myStaticArg1, myStaticArg2, ...));
return expensive;
}
internal protected set
{
expensiveInitialized = true;
expensive = value;
}
}
I am wondering if there's a promise from BCL team that this code is thread-safe? It was not clear from documentation.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
从文档链接:
From the documentation link: