/// <summary> /// Method to add or update item to be cached into the cache /// </summary> /// <param name="key">Cache key</param> /// <param name="value">Value to be cached</param> /// <param name="session">Session key</param> /// <param name="cacheTime">Time after item to be removed from cache</param> /// <returns>Returns boolean indicating if item is added or not</returns> public bool AddOrUpdate(string key, object value, string session, TimeSpan cacheTime) { if (string.IsNullOrEmpty(key)) { throw new ArgumentNullException(nameof(key)); } if (value == null) { throw new ArgumentNullException(nameof(value)); } var cachedItemKey = new CachedItemKey(key, session); Timer timer = new Timer(new TimerCallback(TimerProc), cachedItemKey, cacheTime, TimeSpan.FromMilliseconds(-1)); var addOrUpdatedValue = this.memoryCache.AddOrUpdate(cachedItemKey, value, (cacheKey, oldValue) => oldValue = value); return(addOrUpdatedValue != null); void TimerProc(object state) { var cacheKey = (CachedItemKey)state; this.Remove(cacheKey); } }
/// <summary> /// Removes cached item from in-memory cache /// </summary> /// <param name="key">Cache key</param> /// <param name="session">Session key</param> /// <returns>Returns boolean indicating if cached item is removed or not</returns> public bool Remove(string key, string session) { if (string.IsNullOrEmpty(key)) { throw new ArgumentNullException(nameof(key)); } var cacheKey = new CachedItemKey(key, session); return(this.Remove(cacheKey)); }
/// <summary> /// Internal method to remove cached item from in-memory cache /// </summary> /// <param name="cachedItemKey">Cache key</param> /// <returns>Returns boolean indicating if cached item is removed or not</returns> private bool Remove(CachedItemKey cachedItemKey) { object value = null; if (this.memoryCache?.ContainsKey(cachedItemKey) == true) { this.memoryCache?.TryRemove(cachedItemKey, out value); } return(value != null); }
/// <summary> /// Get cached item from in-memory cache based /// </summary> /// <param name="key">cache key</param> /// <param name="session">session key</param> /// <returns>cached item</returns> public object Get(string key, string session) { if (string.IsNullOrEmpty(key)) { throw new ArgumentNullException(nameof(key)); } object value = null; var cacheKey = new CachedItemKey(key, session); if (this.memoryCache?.ContainsKey(cacheKey) == true) { this.memoryCache?.TryGetValue(cacheKey, out value); } return(value); }