using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Teknik.Utilities { public class ObjectCache { private readonly static ConcurrentDictionary> objectCache = new ConcurrentDictionary>(); private readonly int _cacheSeconds; public ObjectCache(int cacheSeconds) { _cacheSeconds = cacheSeconds; } public T GetObject(string key, Func getObjectFunc) { T foundObject; var cacheDate = DateTime.UtcNow; if (objectCache.TryGetValue(key, out var result) && result.Item1 > cacheDate.Subtract(new TimeSpan(0, 0, _cacheSeconds))) { return (T)result.Item2; } else { foundObject = getObjectFunc(key); // Update the cache for this key if (foundObject != null) UpdateObject(key, foundObject, cacheDate); } return foundObject; } public void UpdateObject(string key, T update) { UpdateObject(key, update, DateTime.UtcNow); } public void UpdateObject(string key, T update, DateTime cacheTime) { objectCache[key] = new Tuple(cacheTime, update); } public void DeleteObject(string key) { objectCache.TryRemove(key, out _); } public bool CacheValid(string key) { if (objectCache.TryGetValue(key, out var result) && result.Item1 > DateTime.UtcNow.Subtract(new TimeSpan(0, 0, _cacheSeconds))) return true; return false; } } }