how to update cached dictionary values in c#

Jul 24 2019 2:55 AM
 
hi guys,
 
 below code  i am caching   dictonary values. i have one doubt if  cached dictionary value changed backend how to update the value here( here i am caching value 20 mins suppose if they update i need to update cached value right)   please help on me guys
 
  
 
Dictionary<string, string> Cache = new Dictionary<string, string>();
var cache = new Cache<string, string>();
// Cache.Add(dictionaryItem.Phrase,TimeSpan.FromMinutes(25))
cache.Store(dictionaryItem.TemplateId.ToString(), dictionaryItem.Phrase, TimeSpan.FromMinutes(20));
// Console.WriteLine();
return dictionaryItem.Phrase;
/////////////
 
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;
}
}