/// <summary> /// Looks for the cache entry that maps to the <paramref name="key"/> value. If it exists (cache hit) it will simply be /// returned. Otherwise, the <paramref name="createItem"/> delegate function will be invoked to create the value. /// It will then get stored it in the cache and set the time-to-live before getting returned. /// </summary> /// <param name="key">The key for the cache entry.</param> /// <param name="createItem">The delegate function that will create the cache entry if it does not exist.</param> /// <returns>The cache entry.</returns> internal TValue GetOrCreate(TKey key, Func <TValue> createItem) { if (TimeToLive <= TimeSpan.Zero) { AKVEventSource.Log.TryTraceEvent("Key caching found disabled, fetching key information."); return(createItem()); } if (!_cache.TryGetValue(key, out TValue cacheEntry)) { AKVEventSource.Log.TryTraceEvent("Cached entry not found, creating new entry."); if (_cache.Count == _maxSize) { _cache.Compact(Max(0.10, 1.0 / _maxSize)); } cacheEntry = createItem(); var cacheEntryOptions = new MemoryCacheEntryOptions { AbsoluteExpirationRelativeToNow = TimeToLive }; _cache.Set(key, cacheEntry, cacheEntryOptions); AKVEventSource.Log.TryTraceEvent("Entry added to local cache."); } else { AKVEventSource.Log.TryTraceEvent("Cached entry found."); } return(cacheEntry); }
public void LazyCache() { using (var cache = new MemoryCache(new MemoryCacheOptions())) { var appcache = new CachingService(new MemoryCacheProvider(cache)); appcache.DefaultCachePolicy = new CacheDefaults { DefaultCacheDurationSeconds = (int)(CacheDuration.TotalSeconds) }; for (int i = 0; i < Rounds; i++) { var tasks = new ConcurrentBag <Task>(); Parallel.ForEach(Keys, key => { Parallel.For(0, Accessors, _ => { appcache.GetOrAdd <SamplePayload>( key, () => { Thread.Sleep(FactoryDurationMs); return(new SamplePayload()); } ); }); }); } // CLEANUP cache.Compact(1); } }
/// <summary> /// Looks for the cache entry that maps to the <paramref name="key"/> value. If it exists (cache hit) it will simply be /// returned. Otherwise, the <paramref name="createItem"/> delegate function will be invoked to create the value. /// It will then get stored it in the cache and set the time-to-live before getting returned. /// </summary> /// <param name="key">The encrypted key bytes.</param> /// <param name="createItem">The delegate function that will decrypt the encrypted column encryption key.</param> /// <returns>The decrypted column encryption key.</returns> internal TValue GetOrCreate(TKey key, Func <TValue> createItem) { if (TimeToLive <= TimeSpan.Zero) { return(createItem()); } if (!cache.TryGetValue(key, out TValue cacheEntry)) { if (cache.Count == maxSize) { cache.Compact(Max(0.10, 1.0 / maxSize)); } cacheEntry = createItem(); var cacheEntryOptions = new MemoryCacheEntryOptions { AbsoluteExpirationRelativeToNow = TimeToLive }; cache.Set(key, cacheEntry, cacheEntryOptions); } return(cacheEntry); }
private void CompactTimer_Elapsed(object Sender, ElapsedEventArgs Args) { Logger.Information("Compacting {@Percentage} Of {@Count} From Memory Cache...", Options.CurrentValue.CacheCompactPercentage, MemoryCache.Count); MemoryCache.Compact(Options.CurrentValue.CacheCompactPercentage); Logger.Information("Compacted Memory Cache To {@Count}.", MemoryCache.Count); }
private void Timer_Elapsed(object Sender, ElapsedEventArgs Args) { Logger.Information("Compacting 50% Of {@Count} From Memory Cache...", MemoryCache.Count); MemoryCache.Compact(50.0); Logger.Information("Compacted Memory Cache To {@Count}.", MemoryCache.Count); }
public IActionResult OnPost() { #region snippet3 _cache.Remove(MyKey); // Remove 33% of cached items. _cache.Compact(.33); cache_size = _cache.Count; #endregion return(Page()); }
// </snippet2> public IActionResult OnPost() { // <snippet3> _cache.Remove(MyKey); // Remove 33% of cached items. _cache.Compact(.33); cache_size = _cache.Count; // </snippet3> return(Page()); }
/// <summary> /// Returns the cache entry corresponding to the specified secret if it exists in the cache. /// Otherwise, the secret value is fetched from Secrets Manager and a new cache entry is created. /// </summary> public SecretCacheItem GetCachedSecret(string secretId) { SecretCacheItem secret = cache.Get <SecretCacheItem>(secretId); if (secret == null) { secret = cache.Set <SecretCacheItem>(secretId, new SecretCacheItem(secretId, secretsManager, config), cacheItemPolicy); if (cache.Count > config.MaxCacheSize) { // Trim cache size to MaxCacheSize, evicting entries using LRU. cache.Compact((double)(cache.Count - config.MaxCacheSize) / cache.Count); } } return(secret); }
protected virtual void Dispose(bool disposing) { if (!disposedValue) { if (disposing) { // TODO: MAYBE FIND A WAY TO CLEAR ALL THE ENTRIES IN THE CACHE (INCLUDING THE ONES WITH A NeverRemove PRIORITY) AND DISPOSE ALL RELATED SEMAPHORES _lockCache.Compact(1.0); _lockCache.Dispose(); } #pragma warning disable CS8625 // Cannot convert null literal to non-nullable reference type. _lockCache = null; #pragma warning restore CS8625 // Cannot convert null literal to non-nullable reference type. disposedValue = true; } }
private void AddMessageToCache(string username, string message) { var msg = new ChatMessage(username, message); var cacheOptions = new MemoryCacheEntryOptions().SetSize(1).SetSlidingExpiration(TimeSpan.FromMinutes(5)); for (var i = 0; i < 50; i++) { if (!_cache.TryGetValue(i, out ChatMessage _)) { _cache.Set(i, msg, cacheOptions); break; } if (_cache.TryGetValue(50, out ChatMessage _)) { _cache.Set(50, msg, cacheOptions); _cache.Compact(.25); } } }
public void SetStreamMemoryCacheValue(object key, Stream stream) { _memoryCache.Compact((double)1 / _cacheOptions.MaxCount); var cacheFilePath = WriteToFile(key, stream); var cts = new CancellationTokenSource(TimeSpan.FromSeconds(_cacheOptions.Expiration)); var cacheEntryOptions = new MemoryCacheEntryOptions { Size = 1, SlidingExpiration = TimeSpan.FromSeconds(_cacheOptions.Expiration), ExpirationTokens = { new CancellationChangeToken(cts.Token) } } .RegisterPostEvictionCallback(ClearCache); _memoryCache.Set(key, new StreamFileCacheItem { CancellationTokenSource = cts, FilePath = cacheFilePath }, cacheEntryOptions); }
static void Main(string[] args) { //cache的最大限制是:100 MemoryCache memoryCache = new MemoryCache(new MemoryCacheOptions() { }); CancellationTokenSource tokenSource = new CancellationTokenSource(); //var cacheOptions = new MemoryCacheEntryOptions() //{ // AbsoluteExpiration = DateTimeOffset.Now.AddSeconds(10), //10s过期 //}; //cacheOptions.RegisterPostEvictionCallback((key, value, reason, obj) => //{ // Console.WriteLine(reason); //}); //cacheOptions.AddExpirationToken(new CancellationChangeToken(tokenSource.Token)); //memoryCache.Set("key", "value", cacheOptions); ////System.Threading.Thread.Sleep(2000); //tokenSource.CancelAfter(1000 * 2); for (int i = 0; i < 100; i++) { memoryCache.Set <string>(i.ToString(), i.ToString(), new MemoryCacheEntryOptions() { }); } memoryCache.Compact(0.2); Console.Read(); }
public async Task LazyCacheCache() { using (var cache = new MemoryCache(new MemoryCacheOptions())) { var appcache = new CachingService(new MemoryCacheProvider(cache)); appcache.DefaultCachePolicy = new CacheDefaults { DefaultCacheDurationSeconds = (int)(CacheDuration.TotalSeconds) }; for (int i = 0; i < Rounds; i++) { var tasks = new ConcurrentBag <Task>(); FactoryCallsCount = 0; // FULL PARALLEL Parallel.ForEach(Keys, key => { Parallel.For(0, Accessors, _ => { var t = appcache.GetOrAddAsync <long>( key, async() => { Interlocked.Increment(ref FactoryCallsCount); await Task.Delay(FactoryDurationMs).ConfigureAwait(false); return(DateTimeOffset.UtcNow.Ticks); } ); tasks.Add(t); }); }); await Task.WhenAll(tasks).ConfigureAwait(false); UpdateExcessiveFactoryCallsStatistics(GetCallerName(), KeysCount, FactoryCallsCount); } cache.Compact(1); } }
public async Task LazyCache() { using (var cache = new MemoryCache(new MemoryCacheOptions())) { var appcache = new CachingService(new MemoryCacheProvider(cache)); appcache.DefaultCachePolicy = new CacheDefaults { DefaultCacheDurationSeconds = (int)(CacheDuration.TotalSeconds) }; for (int i = 0; i < Rounds; i++) { var tasks = new ConcurrentBag <Task>(); Parallel.ForEach(Keys, key => { Parallel.For(0, Accessors, _ => { var t = appcache.GetOrAddAsync <SamplePayload>( key, async() => { await Task.Delay(FactoryDurationMs).ConfigureAwait(false); return(new SamplePayload()); } ); tasks.Add(t); }); }); await Task.WhenAll(tasks).ConfigureAwait(false); } // CLEANUP cache.Compact(1); } }
public void Dispose() { // // Evict the entire cache to trigger handling of disposable resources _cache.Compact(100); if (_cacheEvicter != null) { _cacheEvicter.Dispose(); _cacheEvicter = null; } if (_cache != null) { _cache.Dispose(); _cache = null; } if (_concurrentCacheHelper != null) { _concurrentCacheHelper.Dispose(); _concurrentCacheHelper = null; } }
public void Trim() { _memoryCache.Compact(75); }
public void Handle(ClusterClientMessage.CleanCache message) { _cache.Compact(0); _bus.Publish(TimerMessage.Schedule.Create(_cacheCleaningInterval, _publishEnvelope, new ClusterClientMessage.CleanCache())); }
protected virtual void Compact() { _logger.LogDebug("Cleanup task started. Memory Used : {MemoryUsed}, Memory Limit = {MemoryLimit}", _memoryUsed, _maxSize); _memoryCache.Compact(_options.EvictionPercentage); }
private void TrimCacheToSizeLimit() { versions.Compact((double)(versions.Count - config.MaxCacheSize) / versions.Count); }
/// <summary> /// Removes (almost?) all cached objects. /// </summary> public void Clear() { cache.Compact(1); }
public static void ClearCaches() { _serializeConverters.Compact(1); _deserializeConverters.Compact(1); }
public override void Compact() { _cache.Compact(100); }
public void Clear() => MemoryCache.Compact(100);