protected T GetOrCreateWithLock <T>( string key, Func <T> get, Func <T> factory, CacheOptions <T> options ) { var result = get(); if (result != null) { return(result); } var lockObj = GetLock(key); lock (lockObj) { result = get(); if (result != null) { return(result); } result = factory(); } RemoveLock(key); return(result); }
public virtual Task <HashSet <string> > GetSetAsync( string key, Func <IEnumerable <string> > factory = null ) { var result = GetOrCreateWithLock( key, () => IMemoryCacheService.Get <HashSet <string> >(key), () => { var items = factory != null ? factory() : new string[] { }; var _result = items.ToHashSet(); var entryOptions = new CacheOptions <HashSet <string> >(expirationType: CacheExpirationType.NotRemoveable); IMemoryCacheService.Set(key, _result, entryOptions); return(_result); }, null ); return(Task.FromResult(result)); }
public virtual Task <T> GetAsync <T>( string key, Func <T> factory = null, CacheOptions <T> options = null ) { var result = GetOrCreateWithLock( key, () => IMemoryCacheService.Get <T>(key), () => { if (factory == null) { return(default(T)); } var _result = factory(); IMemoryCacheService.Set(key, _result, options); return(_result); }, options ); return(Task.FromResult(result)); }
public virtual Task SetAsync <T>( string key, T obj, CacheOptions <T> options = null ) { IMemoryCacheService.Set(key, obj, options); return(Task.CompletedTask); }
public MemoryCacheEntryOptions Create <T>(CacheOptions <T> options = null) { var timeoutMinutes = options?.TimeoutMinutes ?? _DefaultTimeoutMinutes; var timeoutMinutesSpan = TimeSpan.FromMinutes(timeoutMinutes); if (options == null) { return new MemoryCacheEntryOptions { SlidingExpiration = timeoutMinutesSpan } } ; var result = new MemoryCacheEntryOptions(); if (options.ExpirationType == CacheExpirationType.NotRemoveable) { result.Priority = CacheItemPriority.NeverRemove; } else { if (options.ExpirationType == CacheExpirationType.Sliding) { result.SlidingExpiration = timeoutMinutesSpan; } if (options.ExpirationType == CacheExpirationType.Absolute) { result.AbsoluteExpirationRelativeToNow = timeoutMinutesSpan; } } result.RegisterPostEvictionCallback((key, value, reason, state) => { options.DidRemove?.Invoke(options); if (value is IDisposable disposable) { disposable.Dispose(); } }); return(result); } #endregion }
public Task SetAsync <T>( string key, T obj, CacheOptions <T> cacheOptions = null ) { return (Task.Run(() => { using (var client = GetClient()) { client.Set(key, obj.ToJsonWithTypeInformation()); if (cacheOptions?.ExpirationType == CacheExpirationType.Absolute) { var absoluteExpire = ITimeService.Now.AddMinutes(cacheOptions.TimeoutMinutes); client.ExpireEntryAt(key, absoluteExpire); } return Task.CompletedTask; } })); }