public T GetOrAdd <T>(string key, Func <T> addItemFactory, CacheItemPolicy policy) { ValidateKey(key); var newLazyCacheItem = new Lazy <T>(addItemFactory); #if NETSTANDARD2_0 EnsureEvictionCallbackDoesNotReturnTheLazy <T>(policy); #else EnsureRemovedCallbackDoesNotReturnTheLazy <T>(policy); #endif var existingCacheItem = ObjectCache.AddOrGetExisting(key, newLazyCacheItem, policy); if (existingCacheItem != null) { return(UnwrapLazy <T>(existingCacheItem)); } try { return(newLazyCacheItem.Value); } catch //addItemFactory errored so do not cache the exception { ObjectCache.Remove(key); throw; } }
public async Task<T> GetOrAddAsync<T>(string key, Func<Task<T>> addItemFactory, CacheItemPolicy policy) { ValidateKey(key); var newLazyCacheItem = new AsyncLazy<T>(addItemFactory); EnsureRemovedCallbackDoesNotReturnTheAsyncLazy<T>(policy); var existingCacheItem = ObjectCache.AddOrGetExisting(key, newLazyCacheItem, policy); if (existingCacheItem != null) return await UnwrapAsyncLazys<T>(existingCacheItem); try { var result = newLazyCacheItem.Value; if (result.IsCanceled || result.IsFaulted) ObjectCache.Remove(key); return await result; } catch //addItemFactory errored so do not cache the exception { ObjectCache.Remove(key); throw; } }
public T GetOrAdd <T>(string key, Func <T> addItemFactory, CacheItemPolicy policy) { ValidateKey(key); var newLazyCacheItem = new Lazy <T>(addItemFactory); EnsureRemovedCallbackDoesNotReturnTheLazy <T>(policy); var existingCacheItem = cache.AddOrGetExisting(key, newLazyCacheItem, policy); if (existingCacheItem != null) { if (existingCacheItem is T) { return((T)existingCacheItem); } if (existingCacheItem is Lazy <T> ) { return(((Lazy <T>)existingCacheItem).Value); } return(default(T)); } try { return(newLazyCacheItem.Value); } catch //addItemFactory errored so do not cache the exception { cache.Remove(key); throw; } }
public T GetOrAdd<T>(string key, Func<T> addItemFactory, CacheItemPolicy policy) { ValidateKey(key); var newLazyCacheItem = new Lazy<T>(addItemFactory); EnsureRemovedCallbackDoesNotReturnTheLazy<T>(policy); var existingCacheItem = ObjectCache.AddOrGetExisting(key, newLazyCacheItem, policy); if (existingCacheItem != null) return UnwrapLazy<T>(existingCacheItem); try { return newLazyCacheItem.Value; } catch //addItemFactory errored so do not cache the exception { ObjectCache.Remove(key); throw; } }