using System; using System.Threading; namespace Jellyfish.Library { public sealed class Lazy where T : class { public Lazy(Func initializer) { _initializer = initializer; } public T Value { get { if (_value == null) { T value = _initializer(); if (Interlocked.CompareExchange(ref _value, value, null) != null) { var disposable = value as IDisposable; // dispose preempted instance if (disposable != null) { disposable.Dispose(); } } } return _value; } } private Func _initializer; private T _value; } }