Question

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.

Was it helpful?

Solution

From the documentation link:

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top