Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Expiring Lazy<T> class

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;
    }
}
like image 826
Anton Avatar asked Oct 18 '22 18:10

Anton


1 Answers

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.

like image 108
Patrick Hofman Avatar answered Oct 21 '22 15:10

Patrick Hofman