Is there any class in .NET library which can act as expiring Lazy<T>
?
The idea is that Func<T>
value factory lambda is passed there and invoked only first time or if timeout is passed.
I've created simple class to do that, but I'd like to avoid inventing a wheel.
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;
}
}
No, there is not an equivalent class in the framework.
Be aware that your class doesn't have the advanced locking, etc. Lazy<T>
has. Take a look at this answer to see how you can effectively do that.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With