.NET库中是否有可以作为过期Lazy<T>
的类?
这个想法是Func<T>
值工厂lambda在那里传递并且只在第一次调用或者超时被传递。
我已经创建了简单的类来做到这一点,但我想避免发明一个轮子。
public class ExpiringLazy<T>
{
private readonly object valueGetLock = new object();
private readonly Func<T> valueFactory;
private readonly TimeSpan timeout;
private T cachedValue;
private DateTime cachedTime;
public T Value
{
get
{
Thread.MemoryBarrier();
if (cachedTime.Equals(default(DateTime)) || DateTime.UtcNow > cachedTime + timeout)
{
lock (valueGetLock)
{
if (cachedTime.Equals(default(DateTime)) || DateTime.UtcNow > cachedTime + timeout)
{
cachedValue = valueFactory();
Thread.MemoryBarrier();
cachedTime = DateTime.UtcNow;
}
}
}
return cachedValue;
}
}
public ExpiringLazy(Func<T> valueFactory, TimeSpan timeout)
{
if (valueFactory == null) throw new ArgumentNullException(nameof(valueFactory));
this.valueFactory = valueFactory;
this.timeout = timeout;
}
}