public async Task <T> GetOrAddAsync <T>(string key, Func <Task <T> > valueFactory, Action <ICacheConfiguration> configurator) { var policy = new CachePolicyFactory().Create(configurator); var asyncLazyValue = new LazyAsync <T>(valueFactory); var existingValue = (LazyAsync <T>)Cache.AddOrGetExisting(KeyPrefix + key, asyncLazyValue, policy); if (existingValue != null) { asyncLazyValue = existingValue; } try { var result = await asyncLazyValue; if (asyncLazyValue != Cache.AddOrGetExisting(KeyPrefix + key, new LazyAsync <T>(valueFactory), policy)) { return(await GetOrAddAsync(KeyPrefix + key, valueFactory, configurator)); } return(result); } catch (Exception) { await RemoveAsync(KeyPrefix + key); throw; } }
private static T AddOrGetExist <T>(string key, T value, double expiredSec, CacheEntryUpdateCallback action = null) { return((T)_cache.AddOrGetExisting(key, value, new CacheItemPolicy() { AbsoluteExpiration = DateTimeOffset.Now.AddSeconds(expiredSec), UpdateCallback = action })); }
protected override object OnAddOrGetExisting(string prefixedKey, object value, DateTimeOffset absoluteExpiration) { var c = new CacheItem(prefixedKey, value); var p = new CacheItemPolicy { AbsoluteExpiration = absoluteExpiration, Priority = System.Runtime.Caching.CacheItemPriority.Default }; var o = _core.AddOrGetExisting(c, p); return(o.Value); }
private static async Task <T> GetOrAddAsync <T>( ObjectCache cache, string key, CacheItemPolicy policy, Func <Task <T> > valueFactory) { var newEntry = new LazyTask <T>(valueFactory); if (cache.AddOrGetExisting(key, newEntry, policy) is LazyTask <T> existingEntry) { return(await existingEntry.Value); } try { Task <T> result = newEntry.Value; if (result.IsCanceled || result.IsFaulted) { cache.Remove(key); } return(await result); } catch { 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 { ObjectCache.Remove(key); throw; } }
private async Task <T> _AddOrGetExistingAsync <T>(string cacheKey, Func <Task <T> > getValueAsync) where T : class { var _newValue = new TaskCompletionSource <T>(); var _cachedValue = _Cache.AddOrGetExisting(cacheKey, _newValue, _CacheItemPolicy) as TaskCompletionSource <T>; if (_cachedValue != null) { return(await _cachedValue.Task); } T _value; try { _value = await getValueAsync(); } catch (Exception _e) { _newValue.SetException(_e); throw; } _newValue.SetResult(_value); return(_value); }
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 { ObjectCache.Remove(key); throw; } }
private ContentSearcher GetSearcher(string contentFolder) { var lazyObj = new Lazy <ContentSearcher>( () => new ContentSearcher(Path.Combine(AppConfig.ContentPath, contentFolder, "Index")).Retain(), LazyThreadSafetyMode.ExecutionAndPublication); object obj = _Cache.AddOrGetExisting(contentFolder, lazyObj, new CacheItemPolicy { RemovedCallback = arguments => ((Lazy <ContentSearcher>)arguments.CacheItem.Value).Value .Release(), SlidingExpiration = TimeSpan.FromMinutes(5) }); if (obj != null) { lazyObj = (Lazy <ContentSearcher>)obj; } return(lazyObj.Value.Retain()); }
/// <summary> /// Verifies role against user's groups in Azure AD /// </summary> /// <param name="role"></param> /// <param name="claimsIdentity"></param> /// <returns></returns> public static async Task <bool> CheckInRole(string role, System.Security.Claims.ClaimsIdentity claimsIdentity) { ObjectCache cache = MemoryCache.Default; try { if (HttpContext.Current.Request.IsAuthenticated) { //use LazyCache to cache the groups var cacheKey = GetCacheKey(claimsIdentity); var groups = cache.AddOrGetExisting(cacheKey, await UserInfoHelper.GetAllGroups(claimsIdentity), _CacheItemPolicy) as List <string>; //locate AD group tied to role if (groups.Count > 0) { return(groups.Contains(ConfigurationManager.AppSettings[role])); } } } catch (Exception) { //TODO: Handle exception } return(false); }
/// <summary> /// This generic form of AddOrGetExisting is an improvement over the non-generic implementation in that this will return /// the value returned by <paramref name="fallbackFunction"/> if it doesn't already exist in the cache. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="cacheProvider"></param> /// <param name="cacheKey"></param> /// <param name="fallbackFunction"></param> /// <param name="policy"></param> /// <returns></returns> public static T AddOrGetExisting <T>(this ObjectCache cacheProvider, string cacheKey, Func <T> fallbackFunction, CacheItemPolicy policy) { object objVal = cacheProvider.Get(cacheKey); if (objVal == null) { var lockObj = new object(); // syncRoot will be null the first time through but is added to cache for the next requests var syncRoot = cacheProvider.AddOrGetExisting("syncroot_" + cacheKey, lockObj, CachingConfig.Policies["syncRootPolicy"].Policy); lock (syncRoot ?? lockObj) { objVal = cacheProvider.Get(cacheKey); if (objVal == null) { objVal = fallbackFunction.Invoke(); // Do not cache nulls if (objVal != null) { cacheProvider.Set(cacheKey, objVal, policy); } } } } return((T)objVal); }
private static CacheEntryChangeMonitor GetChangeMonitor(ObjectCache cache, string[] monitorKeys, string regionName) { if (!monitorKeys.Any()) { return(null); } // Only take the dependencies that currently exist in the cache, some may have been invalidated in the interim. // Also filter out output cache secondary dependencies. var filteredKeys = monitorKeys.Where(key => cache.Contains(key, regionName) && !key.StartsWith(_outputCacheSecondaryDependencyPrefix)).Distinct(); if (!filteredKeys.Any()) { return(null); } // For each output cache dependency, create a secondary dependency, this allows callers to invalidate just the output cache without also invalidating // other cache items which could be in dirty state. var includingSecondaryKeys = new List <string>(); foreach (var filteredKey in filteredKeys) { // Each secondary dependency should be dependent on the primary dependency. var policy = new CacheItemPolicy(); policy.ChangeMonitors.Add(cache.CreateCacheEntryChangeMonitor(new[] { filteredKey }, regionName)); var secondaryDependencyKey = GetSecondaryDependencyKey(filteredKey); cache.AddOrGetExisting(secondaryDependencyKey, string.Empty, policy, regionName); includingSecondaryKeys.Add(secondaryDependencyKey); } includingSecondaryKeys.AddRange(filteredKeys); return(cache.CreateCacheEntryChangeMonitor(includingSecondaryKeys, regionName)); }
/// <summary> /// Dumps everything of a single type into the cache from the database for BackingData /// </summary> /// <typeparam name="T">the type to get and store</typeparam> /// <returns>success status</returns> public static bool PreLoadAll <T>() where T : IData { var backingClass = Activator.CreateInstance(typeof(T)) as IEntityBackingData; var implimentingEntityClass = backingClass.EntityClass; foreach (IData thing in DataWrapper.GetAll <T>()) { var entityThing = Activator.CreateInstance(implimentingEntityClass, new object[] { (T)thing }) as IEntity; var cacheKey = new LiveCacheKey(implimentingEntityClass, entityThing.BirthMark); globalCache.AddOrGetExisting(cacheKey.KeyHash(), entityThing, globalPolicy); } return(true); }
/// <summary> /// Gets from cache. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="key">The key.</param> /// <param name="valueFactory">The value factory.</param> /// <returns></returns> private T GetFromCache <T>(string key, Func <T> valueFactory) { var newValue = new Lazy <T>(valueFactory); // the line belows returns existing item or adds the new value if it doesn't exist var value = _memoryCache.AddOrGetExisting(key, newValue, MemoryCache.InfiniteAbsoluteExpiration); return(((value ?? newValue) as Lazy <T>).Value); // Lazy<T> handles the locking itself }
private bool GetSSLRequirement() { //If the server doesn't support SSL then the requirement will always be false. if (!ServerSupportSSL()) { return(false); } if (IsLoggedIn) { var userId = AstriaCookie.GetUserId(); var requireSSL = true; try { if (userId != Guid.Empty && Cache[userId.ToString()] != null) { return((bool)Cache[userId.ToString()]); } else { ExceptionsML bizEx = null; var client = SvcBldr.Company(); var settings = client.GetSettingsByName(Constants.REQUIRESSL, out bizEx); if (bizEx == null) { var setting = settings.First(); requireSSL = bool.Parse(setting.Value); } else if (bizEx.Type == typeof(LoginRequiredException).ToString()) { SignOut(bizEx.Data); } } } catch { } Cache.AddOrGetExisting(userId.ToString(), requireSSL, new CacheItemPolicy() { AbsoluteExpiration = DateTimeOffset.Now.AddMinutes(1) }); return(requireSSL); } else { return(true); } }
private static void AddTag(ObjectCache cache, DateTime now, DateTime tagExpiration, string item) { cache.AddOrGetExisting(item, now, new CacheItemPolicy { Priority = CacheItemPriority.NotRemovable, AbsoluteExpiration = tagExpiration, RemovedCallback = CacheTagRemovedCallBack }); }
public T AddOrGet <T>(string key, int expirationMinutes, Func <T> repository) { var newValue = new Lazy <T>(repository); var oldValue = _cache.AddOrGetExisting(key, newValue, new CacheItemPolicy { AbsoluteExpiration = DateTime.UtcNow.AddMinutes(expirationMinutes) }) as Lazy <T>; try { return((oldValue ?? newValue).Value); } catch (Exception) { _cache.Remove(key); throw; } }
private bool hasNotVisitedLink(string key, Uri value) { bool hasNotVisited = _cache.AddOrGetExisting(key, value, policy: new CacheItemPolicy() { Priority = CacheItemPriority.NotRemovable }) == null; return(hasNotVisited); }
/// <summary> /// Adds the sport event status to the internal cache /// </summary> /// <param name="eventId">The eventId of the sport event status to be cached</param> /// <param name="sportEventStatus">The sport event status to be cached</param> /// <param name="statusOnEvent">The sport event status received directly on event level</param> /// <param name="source">The source of the SES</param> // ReSharper disable once UnusedParameter.Local private void AddSportEventStatus(URN eventId, SportEventStatusCI sportEventStatus, string statusOnEvent, string source) { if (_isDisposed) { return; } if (sportEventStatus == null) { return; } Guard.Argument(eventId, nameof(eventId)).NotNull(); if (string.IsNullOrEmpty(source) || source.Equals("OddsChange", StringComparison.InvariantCultureIgnoreCase) || source.Equals("SportEventSummary", StringComparison.InvariantCultureIgnoreCase) || !_sportEventStatusCache.Contains(eventId.ToString())) { lock (_lock) { if (!string.IsNullOrEmpty(source)) { if (OperationManager.IgnoreBetPalTimelineSportEventStatus && source.Contains("Timeline") && _ignoreEventsTimelineCache.Contains(eventId.ToString())) { ExecutionLog.Debug($"Received SES for {eventId} from {source} with EventStatus:{sportEventStatus.Status} (timeline ignored)"); return; } source = $" from {source}"; } ExecutionLog.Debug($"Received SES for {eventId}{source} with EventStatus:{sportEventStatus.Status}"); var cacheItem = _sportEventStatusCache.AddOrGetExisting(eventId.ToString(), sportEventStatus, new CacheItemPolicy { AbsoluteExpiration = DateTimeOffset.Now.AddSeconds(OperationManager.SportEventStatusCacheTimeout.TotalSeconds) }) as SportEventStatusCI; if (cacheItem != null) { cacheItem.SetFeedStatus(sportEventStatus.FeedStatusDTO); cacheItem.SetSapiStatus(sportEventStatus.SapiStatusDTO); } } } else { ExecutionLog.Debug($"Received SES for {eventId} from {source} with EventStatus:{sportEventStatus.Status} (ignored)"); } }
private bool NotPresentInCache(string key, Uri value) { var hasNotVisited = _memoryCache.AddOrGetExisting(key, value, policy: new CacheItemPolicy() { Priority = CacheItemPriority.NotRemovable }) == null; return(hasNotVisited); }
public T GetOrAdd <T>(string key, Func <T> valueFactory) { var newValue = new Lazy <T>(valueFactory, LazyThreadSafetyMode.PublicationOnly); CacheItemPolicy policy = new CacheItemPolicy() { SlidingExpiration = _timeOut }; var value = (Lazy <T>)_cache.AddOrGetExisting(key, newValue, policy); return((value ?? newValue).Value); }
public static TEntity Get <TEntity>(string key, Func <TEntity> func, double expire = 2) { ObjectCache cache = MemoryCache.Default; var newValue = new Lazy <TEntity>(func); var policy = new CacheItemPolicy { AbsoluteExpiration = DateTimeOffset.Now.AddMinutes(expire) }; var value = cache.AddOrGetExisting(key, newValue, policy) as Lazy <TEntity>; return((value ?? newValue).Value); }
public void AddOrInsertCachedItem() { ObjectCache cache = MemoryCache.Default; var policy = new CacheItemPolicy() { SlidingExpiration = TimeSpan.FromMinutes(1) }; var value = cache.AddOrGetExisting <int>("foo", () => { return(1); }, policy); Assert.AreEqual(1, value); }
private static object GetCacheData(TakeOperation operation, IContentQuery <TextContent> contentQuery, CacheItemPolicy policy, Func <object> getData) { string cacheKey = "TakeOperation:" + operation.ToString() + " " + TextTranslator.Translate(contentQuery); var data = ObjectCache.Get(cacheKey, CacheRegionName); if (data == null) { data = getData(); ObjectCache.AddOrGetExisting(cacheKey, data, policy, CacheRegionName); } return(data); }
private static TEntity GetFromCache <TEntity>(string key, Func <TEntity> valueFactory) where TEntity : class { ObjectCache cache = MemoryCache.Default; // the lazy class provides lazy initializtion which will eavaluate the valueFactory expression only if the item does not exist in cache var newValue = new Lazy <TEntity>(valueFactory); CacheItemPolicy policy = new CacheItemPolicy { AbsoluteExpiration = DateTimeOffset.Now.AddMinutes(30), Priority = CacheItemPriority.NotRemovable }; //The line below returns existing item or adds the new value if it doesn't exist var value = cache.AddOrGetExisting(key, newValue, policy) as Lazy <TEntity>; return((value ?? newValue).Value); // Lazy<T> handles the locking itself }
/// <summary> /// Adds a cache entry into the cache using the specified key and a Valuefactory and an absolute expiration value /// </summary> /// <param name="cache">The cache.</param> /// <param name="key">A unique identifier for the cache entry to add.</param> /// <param name="valueFactory">The value factory.</param> /// <param name="absoluteExpiration">The fixed date and time at which the cache entry will expire.</param> /// <param name="regionName">A named region in the cache to which a cache entry can be added. Do not pass a value for this parameter. This parameter is null by default, because the MemoryCache class does not implement regions.</param> /// <returns>If a cache entry with the same key exists, the existing cache entry; otherwise, null.</returns> public static T AddOrGetExisting <T>(this ObjectCache cache, string key, Func <T> valueFactory, DateTimeOffset absoluteExpiration = default(DateTimeOffset), string regionName = null) { if (absoluteExpiration == default(DateTimeOffset)) { absoluteExpiration = ObjectCache.InfiniteAbsoluteExpiration; } Lazy <T> newValue = new Lazy <T>(valueFactory); Lazy <T> value = (Lazy <T>)cache.AddOrGetExisting(key, newValue, absoluteExpiration, regionName); return((value ?? newValue).Value); }
public TEntity GetSingleFromCache <TEntity>(string key, string refreshPeriodkey, TEntity valueFactory) where TEntity : class { var mints = int.Parse(ConfigurationManager.AppSettings[refreshPeriodkey]); ObjectCache cache = MemoryCache.Default; var newValue = valueFactory; CacheItemPolicy policy = new CacheItemPolicy { AbsoluteExpiration = DateTimeOffset.Now.AddMinutes(mints) }; //The line below returns existing item or adds the new value if it doesn't exist var value = cache.AddOrGetExisting(key, newValue, policy) as TEntity; return(value ?? newValue); // Lazy<T> handles the locking itself }
// Token: 0x06000082 RID: 130 RVA: 0x00004604 File Offset: 0x00002804 public Entry UpdateCache(ObjectCache cache) { CacheItem value = this.GetCacheItem(); CacheItem cacheItem = cache.AddOrGetExisting(value, this.GetCachePolicy()); if (cacheItem.Value != null) { Entry entry = cacheItem.Value as Entry; this.UpdateExistingEntry(entry); return(entry); } return(this); }
static void Main(string[] args) { ObjectCache objCache = MemoryCache.Default; var policy = new CacheItemPolicy(); var cacheId = AddIntoCache(objCache, policy); Console.WriteLine(GetValueFromCache(objCache, cacheId)); var cacheeId = Guid.NewGuid().ToString(); var output = objCache.AddOrGetExisting(cacheeId, 100, policy); Console.WriteLine(output); Console.WriteLine(GetValueFromCache(objCache, cacheeId)); Console.ReadKey(); }
/// <summary> /// either returns an exesiting cache value or it creates a new one and returns the value /// </summary> /// <typeparam name="TEntity"></typeparam> /// <param name="cache"></param> /// <param name="key"></param> /// <param name="valueFactory"></param> /// <param name="policy"></param> /// <returns></returns> public static TEntity AddOrGetExistingCacheEntry <TEntity>(this ObjectCache cache, string key, Func <TEntity> valueFactory, CacheItemPolicy policy) { Lazy <TEntity> newValue = new Lazy <TEntity>(valueFactory); Lazy <TEntity> oldValue = (Lazy <TEntity>)cache.AddOrGetExisting(key, newValue, policy); try { return(oldValue != null ? oldValue.Value : newValue.Value); } catch { cache.Remove(key); throw; } }
/// <summary> /// inserts a lazily, asynchronously initialized cache entry into the cache, specifying a key and a value for the cache entry, /// and information about how the entry will be evicted. /// </summary> /// <typeparam name="T">The element type.</typeparam> /// <param name="cache">The cache.</param> /// <param name="key">A unique identifier for the cache entry.</param> /// <param name="valueFactory">The value factory method.</param> /// <param name="policy">An object that contains eviction details for the cache entry.</param> /// <returns>The cached value.</returns> public static async Task <T> AddOrGetExistingAsync <T>(this ObjectCache cache, string key, Func <Task <T> > valueFactory, CacheItemPolicy policy) { var newValue = new AsyncLazy <T>(valueFactory); var oldValue = cache.AddOrGetExisting(key, newValue, policy) as Lazy <T>; try { return(oldValue != null ? oldValue.Value : await newValue.Value); } catch { cache.Remove(key); throw; } }