具有过期时间的字典缓存

Dai*_*ges 2 c# caching dictionary unit-testing

我想创建一个返回值的类。此值将在字典对象中缓存2分钟。在这2分钟内,我需要返回缓存的值,在那几分钟之后,字典缓存对象应再次读取该值。我需要使用Dictionary对象而不是memorychache之类的东西,并且应该在Test方法类中执行代码,而不是Windows窗体或wpf。

我不知道在测试方法中2分钟后如何使字典对象过期。

public class CacheClass
{
   public string GetValue()
   {
      Dictionary<int, string> Cache = new Dictionary<int, string>();
      string value1 = "Lina";
      string value2 = "Jack";

      return "cached value";
   }
}
Run Code Online (Sandbox Code Playgroud)

Sco*_*nen 7

public class Cache<TKey, TValue>
{
    private readonly Dictionary<TKey, CacheItem<TValue>> _cache = new Dictionary<TKey, CacheItem<TValue>>();

    public void Store(TKey key, TValue value, TimeSpan expiresAfter)
    {
        _cache[key] = new CacheItem<TValue>(value, expiresAfter);
    }

    public TValue Get(TKey key)
    {
        if (!_cache.ContainsKey(key)) return default(TValue);
        var cached = _cache[key];
        if (DateTimeOffset.Now - cached.Created >= cached.ExpiresAfter)
        {
            _cache.Remove(key);
            return default(TValue);
        }
        return cached.Value;
    }
}

public class CacheItem<T>
{
    public CacheItem(T value, TimeSpan expiresAfter)
    {
        Value = value;
        ExpiresAfter = expiresAfter;
    }
    public T Value { get; }
    internal DateTimeOffset Created { get; } = DateTimeOffset.Now;
    internal TimeSpan ExpiresAfter { get; }
}

var cache = new Cache<int, string>();
cache.Store(1, "SomeString", TimeSpan.FromMinutes(2));
Run Code Online (Sandbox Code Playgroud)

  • 您不希望单元测试运行两分钟。理想情况下,有一些抽象是好的,这样就不会对某些 `.Now` 属性产生严重依赖。但在这种情况下,引入会使答案变得非常复杂。在现实生活中,我可能只是使用 &lt;50 毫秒的缓存持续时间和一个“Thread.Sleep(200)”来测试它,类似的东西。 (2认同)