Expires Lazy <T> class

Is there any class in the .NET library that can act as expiring Lazy<T>?

The idea is that Func<T>the factory lambda value is passed there and called only for the first time or if the timeout is passed.

I created a simple class for this, but I would like not to reinvent the 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;
    }
}
+4
source share
1 answer

No, there is no equivalent class in the structure.

Remember that your class does not have extended locking, etc. Lazy<T>It has. See this answer to find out how you can do this effectively.

+3
source

Source: https://habr.com/ru/post/1624288/


All Articles