LazyInitializer.EnsureInitialized是否有效?有线程安全的明确承诺吗?

发布于 2024-11-06 14:16:53 字数 709 浏览 4 评论 0原文

我想创建一个可以通过属性注入进行测试的惰性属性。如果我要使用惰性字段,我不知道如何在测试期间注入自己的字段。这是我的代码:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

有深☉意 2024-11-13 14:16:54

从文档链接:

LazyInitializer 的方法是线程安全的,可以从多个线程同时调用。

From the documentation link:

The methods of LazyInitializer are thread-safe and may be called from multiple threads concurrently.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文