2009-05-22 14:37:50 +00:00
|
|
|
|
using System;
|
|
|
|
|
using System.Threading;
|
|
|
|
|
|
|
|
|
|
namespace Jellyfish.Library
|
|
|
|
|
{
|
2009-07-26 23:22:00 +00:00
|
|
|
|
public sealed class Lazy<T> where T : class
|
2009-05-22 14:37:50 +00:00
|
|
|
|
{
|
|
|
|
|
public Lazy(Func<T> initializer)
|
|
|
|
|
{
|
|
|
|
|
_initializer = initializer;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public T Value
|
|
|
|
|
{
|
|
|
|
|
get
|
|
|
|
|
{
|
|
|
|
|
if (_value == null)
|
|
|
|
|
{
|
|
|
|
|
T value = _initializer();
|
|
|
|
|
if (Interlocked.CompareExchange(ref _value, value, null) != null)
|
|
|
|
|
{
|
|
|
|
|
IDisposable disposable = value as IDisposable; // dispose preempted instance
|
|
|
|
|
if (disposable != null)
|
|
|
|
|
{
|
|
|
|
|
disposable.Dispose();
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return _value;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
private Func<T> _initializer;
|
|
|
|
|
private T _value;
|
|
|
|
|
}
|
|
|
|
|
}
|