125 lines
2.6 KiB
C#
125 lines
2.6 KiB
C#
using System;
|
|
using System.Threading;
|
|
using JD.Kernel.StaticHelpers;
|
|
|
|
namespace JD.Reflection.Interfaces
|
|
{
|
|
public class Lazy<T>
|
|
{
|
|
#region Variables
|
|
|
|
private readonly object m_lock;
|
|
private T m_value;
|
|
private volatile bool m_isValueCreated;
|
|
private Func<T> m_valueFactory;
|
|
|
|
#endregion
|
|
|
|
#region Constructor
|
|
|
|
public Lazy(T value)
|
|
{
|
|
m_lock = null;
|
|
m_value = value;
|
|
m_isValueCreated = true;
|
|
m_valueFactory = null;
|
|
}
|
|
|
|
public Lazy(Func<T> valueFactory) :
|
|
this(valueFactory, true)
|
|
{
|
|
}
|
|
|
|
public Lazy(Func<T> valueFactory, bool isThreadSafe)
|
|
{
|
|
Throw.IfNull(valueFactory, "valueFactory");
|
|
|
|
if (isThreadSafe)
|
|
{
|
|
m_lock = new object();
|
|
}
|
|
|
|
m_valueFactory = valueFactory;
|
|
}
|
|
|
|
#endregion
|
|
|
|
#region Properties
|
|
|
|
public T Value
|
|
{
|
|
get
|
|
{
|
|
if (!m_isValueCreated)
|
|
{
|
|
if (m_lock != null)
|
|
{
|
|
Monitor.Enter(m_lock);
|
|
}
|
|
|
|
try
|
|
{
|
|
T value = m_valueFactory();
|
|
m_valueFactory = null;
|
|
Thread.MemoryBarrier();
|
|
m_value = value;
|
|
m_isValueCreated = true;
|
|
}
|
|
finally
|
|
{
|
|
if (m_lock != null)
|
|
{
|
|
Monitor.Exit(m_lock);
|
|
}
|
|
}
|
|
}
|
|
return m_value;
|
|
}
|
|
}
|
|
|
|
#endregion
|
|
}
|
|
|
|
public class Lazy<T, TMetadata> : Lazy<T>
|
|
{
|
|
#region Variables
|
|
|
|
private readonly TMetadata m_metadata;
|
|
|
|
#endregion
|
|
|
|
#region Constructor
|
|
|
|
public Lazy(T value, TMetadata metadata) :
|
|
base(value)
|
|
{
|
|
m_metadata = metadata;
|
|
}
|
|
|
|
public Lazy(Func<T> valueFactory, TMetadata metadata) :
|
|
base(valueFactory)
|
|
{
|
|
m_metadata = metadata;
|
|
}
|
|
|
|
public Lazy(Func<T> valueFactory, TMetadata metadata, bool isThreadSafe) :
|
|
base(valueFactory, isThreadSafe)
|
|
{
|
|
m_metadata = metadata;
|
|
}
|
|
|
|
#endregion
|
|
|
|
#region Properties
|
|
|
|
public TMetadata Metadata
|
|
{
|
|
get
|
|
{
|
|
return m_metadata;
|
|
}
|
|
}
|
|
|
|
#endregion
|
|
}
|
|
}
|