到期Lazy <t> class

时间:2016-01-14 14:21:00

标签: c# .net base-class-library

.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;
    }
}

1 个答案:

答案 0 :(得分:3)

不,框架中没有等效的类。

请注意,您的班级没有高级锁定,等等Lazy<T>。看看this answer,了解如何有效地做到这一点。