Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dictionary Cache with expiration time

I want to create a class to return a value. This value will be cached in a dictionary object for 2 minutes. During these 2 minutes I need to return the cached value, after those minutes the dictionary cache object should read the value again. I need to use the Dictionary object not memorychache or something and I should execute the code in Test method class not a windows form or wpf.

I don't know how to make the dictionary object expired after 2 minutes in a test method.

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

      return "cached value";
   }
}
like image 826
Daina Hodges Avatar asked Dec 18 '17 18:12

Daina Hodges


1 Answers

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));
like image 120
Scott Hannen Avatar answered Sep 28 '22 12:09

Scott Hannen