public static SmartCache CreateCache(string name, Func <string, object> f, TimeSpan refresh, TimeSpan clear) { lock (Caches) { if (!Caches.ContainsKey(name)) { var cache = new SmartCache(f, refresh, clear); Caches.Add(name, cache); } else { var cache = Caches[name]; if (cache.RefreshTime != refresh) { cache.RefreshTime = refresh; } if (cache.ClearTime != clear) { cache.ClearTime = clear; } } } return(Caches[name]); }
public IActionResult Get(string key) { if (!Caches.ContainsKey(key)) { return(null); } return(Caches[key]); }
public bool Set(string key, IActionResult data, int expireTime = -1) { if (Caches.ContainsKey(key)) { Caches[key] = data; } else { Caches.Add(key, data); } return(true); }
/// <summary> /// Creates the discovery cache. /// </summary> /// <returns>DiscoCache.</returns> public static DiscoCache CreateDiscoCache(string ecoSpaceUrl = null) { if (String.IsNullOrWhiteSpace(ecoSpaceUrl)) { ecoSpaceUrl = ConfigurationHelper.DiscoEndpoint; } if (Caches.ContainsKey(ecoSpaceUrl)) { return(Caches[ecoSpaceUrl]); } var c = new DiscoCache() { EcoSpaceUrl = ecoSpaceUrl }; Caches.Add(ecoSpaceUrl, c); return(c); }
/// <summary> /// Get the <see cref="CachedData"/> from caches if it exists /// </summary> /// <param name="key"></param> /// <param name="lockData"></param> /// <returns></returns> public CachedData GetData(string key, bool lockData) { lock (lockObj) { if (Caches.ContainsKey(key)) { var data = Caches[key]; if (lockData) { data.Lock(); } return(data); } } return(null); }
private void DataOnDisposed(object sender, EventArgs e) { var data = (CachedData)sender; data.Disposed -= DataOnDisposed; lock (lockObj) { if (Caches.ContainsKey(data.Key)) { File.Delete(data.Path); TotalSize -= data.Size; TotalCount--; Caches.Remove(data.Key); data.Path = null; data.Key = null; } } Removed?.Invoke(this, new CachedEventArgs(data)); }
/// <summary> /// Enforce the manager to add/update cache from <see cref="CacheFactory"/> /// </summary> /// <param name="key"></param> /// <param name="factory"></param> /// <returns></returns> public async Task <CachedData> CacheAsync(string key, CacheFactory factory, bool lockData) { CachedData data = new CachedData(key); await data.Semaphore.WaitAsync(); CachedData caching = null; lock (lockObj) { if (Caching.ContainsKey(key)) { caching = Caching[key]; } else { data.Lock(); Caching.Add(key, data); } } if (caching != null) { await caching.Semaphore.WaitAsync(); caching.Semaphore.Release(); return(caching); } using (var fs = AllocateTemporaryFile(factory, out var path)) { await factory.Factory(fs); data.Path = path; data.Size = fs.Length; TotalSize += fs.Length; TotalCount++; } CachedData last = null; lock (lockObj) { Caching.Remove(key); if (Caches.ContainsKey(key)) { last = Caches[key]; } data.Disposed += DataOnDisposed; Caches[key] = data; } last?.Dispose(); CheckCaches(); if (!lockData) { data.Unlock(); } data.Semaphore.Release(); Cached?.Invoke(this, new CachedEventArgs(data)); return(data); }