What is the thread safe way to dispose a lazy-initialized object in C#? Suppose I have the following Lazy construct:
Lazy<MyClass> lazy = new Lazy<MyClass>(() => MyClass.Create(), true);
Later, I might want to dispose the MyClass instance created. Most existing solutions recommend something like this:
if (lazy.IsValueCreated)
{
lazy.Value.Dispose();
}
But as far as I can tell IsValueCreated does not hold any locks: https://referencesource.microsoft.com/#mscorlib/system/Lazy.cs,284
This means another thread may be in the process of initializing MyClass when we check for IsValueCreated. In that case we will observe IsValueCreated to be false, and end up leaking a resource. What is the right course of action here? Or have I missed some subtle detail?