public Task <long> Increment(string key, long value = 1, TimeSpan?expire = null) { bool taken = false; try { spinLock.Enter(ref taken); if (!_cache.TryGetValue(key, out object result)) { result = 0L; var entry = _cache.CreateEntry(key); entry.SetValue(result); if (expire != null) { entry.SetAbsoluteExpiration(expire.Value); } entry.Dispose(); } var n = (long)result; n += value; _cache.Set(key, n); return(Task.FromResult <long>(n)); } finally { if (taken) { spinLock.Exit(); } } }
/// <summary> /// Add the specified scope to the cache. /// </summary> /// <param name="scope">The scope to add to the cache.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> that can be used to abort the operation.</param> /// <returns> /// A <see cref="Task"/> that can be used to monitor the asynchronous operation. /// </returns> public async Task AddAsync([NotNull] TScope scope, CancellationToken cancellationToken) { if (scope == null) { throw new ArgumentNullException(nameof(scope)); } _cache.Remove(new { Method = nameof(FindByIdAsync), Identifier = await _store.GetIdAsync(scope, cancellationToken) }); _cache.Remove(new { Method = nameof(FindByNameAsync), Name = await _store.GetNameAsync(scope, cancellationToken) }); foreach (var resource in await _store.GetResourcesAsync(scope, cancellationToken)) { _cache.Remove(new { Method = nameof(FindByResourceAsync), Resource = resource }); } var signal = await CreateExpirationSignalAsync(scope, cancellationToken); if (signal == null) { throw new InvalidOperationException("An error occurred while creating an expiration token."); } using (var entry = _cache.CreateEntry(new { Method = nameof(FindByIdAsync), Identifier = await _store.GetIdAsync(scope, cancellationToken) })) { entry.AddExpirationToken(signal) .SetSize(1L) .SetValue(scope); } using (var entry = _cache.CreateEntry(new { Method = nameof(FindByNameAsync), Name = await _store.GetNameAsync(scope, cancellationToken) })) { entry.AddExpirationToken(signal) .SetSize(1L) .SetValue(scope); } }
//public object this[string key] { get => Get(key); set => Set(key, value); } public override bool Add(string key, object value, DateTimeOffset?absoluteExpiration = null) { var entry = _cache.CreateEntry(key); entry.AbsoluteExpiration = absoluteExpiration; entry.SetValue(value); entry.Dispose(); return(true); }
public void GetOrCreateTest1() { IMemoryCache cache = new MemoryCache(new MemoryCacheOptions()); cache.CreateEntry(1).SetValue("Alexander"); cache.CreateEntry(2).SetValue("John"); var value = cache.GetOrCreate(3, () => { return("Anna"); }); Assert.Equal("Anna", value); }
public void FirstOrDefaultTest2() { IMemoryCache cache = new MemoryCache(new MemoryCacheOptions()); cache.CreateEntry(1).SetValue(new User(1, "Alex", "*****@*****.**", 20)); cache.CreateEntry(2).SetValue(new User(2, "John", "*****@*****.**", 30)); var value = cache.FirstOrDefault <User>(o => o.Name.Equals("Anna")); Assert.Null(value); }
public void FirstOrDefaultTest() { IMemoryCache cache = new MemoryCache(new MemoryCacheOptions()); var obj = new object(); cache.CreateEntry(1).SetValue("Alexander"); cache.CreateEntry(2).SetValue(obj); cache.CreateEntry(3).SetValue("Anna"); Assert.NotNull(cache.FirstOrDefault(o => o.Equals(obj))); }
public void TryGetEntryTest2() { IMemoryCache cache = new MemoryCache(new MemoryCacheOptions()); var entry = cache.CreateEntry(1); entry.Value = new object(); cache.CreateEntry(1); var result = cache.TryGetEntry(1, out var value); Assert.True(result); Assert.NotEqual(entry, value); }
public void GetOrCreateTest1() { IMemoryCache cache = new MemoryCache(new MemoryCacheOptions()); var obj = new object(); cache.CreateEntry(1).SetValue(obj); cache.CreateEntry(2).SetValue("John"); var value = cache.GetOrCreate(1, () => obj); Assert.Equal(obj, value); }
public void LimitTest2() { IMemoryCache cache = new MemoryCache( new MemoryCacheOptions() { EntriesSizeLimit = 3, }); cache.CreateEntry(1).SetPriority(CacheItemPriority.NeverRemove); cache.CreateEntry(2).SetPriority(CacheItemPriority.NeverRemove); cache.CreateEntry(3).SetPriority(CacheItemPriority.NeverRemove); Assert.Throws <IndexOutOfRangeException>(() => { cache.CreateEntry(4); }); Assert.False(cache.TrySet(4, new CacheEntry(4))); }
public void FindAllTest2() { IMemoryCache cache = new MemoryCache(new MemoryCacheOptions()); cache.CreateEntry(1).SetValue(new User(1, "Alex", "*****@*****.**", 20)); cache.CreateEntry(2).SetValue("Joe"); cache.CreateEntry(3).SetValue("Barney"); cache.CreateEntry(4).SetValue(new User(4, "John", "*****@*****.**", 30)); cache.CreateEntry(5).SetValue(new User(5, "Anna", "*****@*****.**", 32)); var collection = cache.FindAll <User>(o => o != null); Assert.NotEmpty(collection); Assert.Equal(3, collection.Count()); }
public void GetOrCreateTest3() { IMemoryCache cache = new MemoryCache(new MemoryCacheOptions()); cache.CreateEntry(1).SetValue(new User(1, "Alex", "*****@*****.**", 20)); cache.CreateEntry(2).SetValue(new User(2, "John", "*****@*****.**", 30)); var value = cache.GetOrCreate <User>(3, entry => { entry.SetValue(new User(3, "Anna", "*****@*****.**", 32)); }); Assert.NotNull(value); Assert.Equal("Anna", value.Name); }
public async Task GetOrCreateAsyncTest3() { IMemoryCache cache = new MemoryCache(new MemoryCacheOptions()); cache.CreateEntry(1).SetValue("Alexander"); cache.CreateEntry(2).SetValue("John"); var value = await cache.GetOrCreateAsync(1, async entry => { await Task.Delay(1000); entry.SetValue("Anna"); }); Assert.Equal("Alexander", value); }
public void FindAllTest() { IMemoryCache cache = new MemoryCache(new MemoryCacheOptions()); var obj = new object(); cache.CreateEntry(1).SetValue("Alexander"); cache.CreateEntry(2).SetValue(obj); cache.CreateEntry(3).SetValue(obj); var collection = cache.FindAll(o => o.Equals(obj)); Assert.NotEmpty(collection); Assert.Equal(2, collection.Count()); }
/// <summary> /// 创建cache值 /// </summary> /// <param name="phone"></param> /// public void CreateKey(string key, string value) { using (var entry = Cache.CreateEntry(key)) { entry.Value = value; } }
static void ChangeTokenTest() { string inner = "inner"; string outer = "outer"; var cts = new CancellationTokenSource(); IMemoryCache cache = new MemoryCache(new MemoryCacheOptions()); using (var entry = cache.CreateEntry(outer)) { entry.Value = DateTime.Now; cache.Set(inner, DateTime.Now.AddMinutes(1), new CancellationChangeToken(cts.Token)); } Console.WriteLine(cache.Get <DateTime?>(outer)); Console.WriteLine(cache.Get <DateTime?>(inner)); cts.Cancel(); Console.WriteLine("cleared"); Console.WriteLine(cache.Get <DateTime?>(outer)); Console.WriteLine(cache.Get <DateTime?>(inner)); }
public void ImportSite() { if (cache.TryGetValue("HackerNewsPage", out IPage page)) { _page = page; } else { _page = new HackerNewsPage(); // Load up all the news items in the 'Data' layer, filter on the 'UI' var importUrls = new List <string> { "https://news.ycombinator.com/news?p=1", "https://news.ycombinator.com/news?p=2", "https://news.ycombinator.com/news?p=3", "https://news.ycombinator.com/news?p=4" }; foreach (var importUrl in importUrls) { var web = new HtmlWeb(); var htmlDoc = web.Load(importUrl); _page.IngestPage(htmlDoc); } var entry = cache.CreateEntry("HackerNewsPage"); entry.AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(20); entry.SetValue(_page); entry.Dispose(); } }
static void DependencyTest() { IMemoryCache cache = new MemoryCache(new MemoryCacheOptions()); string inner = "inner"; string outer = "outer"; using (var entry = cache.CreateEntry(outer)) { entry.Value = DateTime.Now; //entry.AbsoluteExpirationRelativeToNow = TimeSpan.FromSeconds(10); //会被 inner 覆盖 cache.Set(inner, DateTime.Now.AddMinutes(1), TimeSpan.FromSeconds(5)); } int i = 0; while (true) { Thread.Sleep(1000); Console.WriteLine(cache.Get <DateTime?>(outer)); Console.WriteLine(cache.Get <DateTime?>(inner)); Console.WriteLine(i++); Console.WriteLine(); if (!cache.TryGetValue(inner, out DateTime value) && !cache.TryGetValue(outer, out DateTime value2)) { break; } } Console.WriteLine(cache.Get <DateTime?>(outer)); Console.WriteLine(cache.Get <DateTime?>(inner)); //如果 using 不用括号会执行到这里才释放 }
public void GetCollectionTest1() { IMemoryCache cache = new MemoryCache(new MemoryCacheOptions()); cache.CreateEntry(1); cache.CreateEntry(2); cache.CreateEntry(3); var collection = cache.GetCacheCollection(); cache.Remove(1); Assert.NotEmpty(collection); Assert.Equal(3, collection.Count()); Assert.False(cache.ContainsKey(1)); }
public void CacheEntryDependencies() { var cts = new CancellationTokenSource(); var pause = new ManualResetEvent(false); using (var cacheEntry = _memoryCache.CreateEntry(_cacheKey)) { _memoryCache.Set("master key", "some value", new MemoryCacheEntryOptions() .AddExpirationToken(new CancellationChangeToken(cts.Token))); cacheEntry.SetValue(_cacheItem) .RegisterPostEvictionCallback( (key, value, reason, substate) => { _result = $"'{key}':'{value}' was evicted because: {reason}"; pause.Set(); } ); } // trigger the token to expire the master item cts.Cancel(); Assert.True(pause.WaitOne(500)); Assert.Equal("'key':'value' was evicted because: TokenExpired", _result); }
private async Task <IHtmlContent> CreateCacheEntry(CacheTagKey cacheKey, TagHelperOutput output) { var tokenSource = new CancellationTokenSource(); var options = GetMemoryCacheEntryOptions(); options.AddExpirationToken(new CancellationChangeToken(tokenSource.Token)); options.SetSize(PlaceholderSize); var tcs = new TaskCompletionSource <IHtmlContent>(); // The returned value is ignored, we only do this so that // the compiler doesn't complain about the returned task // not being awaited var localTcs = MemoryCache.Set(cacheKey, tcs.Task, options); try { // The entry is set instead of assigning a value to the // task so that the expiration options are not impacted // by the time it took to compute it. // Use the CreateEntry to ensure a cache scope is created that will copy expiration tokens from // cache entries created from the GetChildContentAsync call to the current entry. IHtmlContent content; var entry = MemoryCache.CreateEntry(cacheKey); // The result is processed inside an entry // such that the tokens are inherited. var result = ProcessContentAsync(output); content = await result; options.SetSize(GetSize(content)); entry.SetOptions(options); entry.Value = result; tcs.SetResult(content); // An entry gets committed to the cache when disposed gets called. We only want to do this when // the content has been correctly generated (didn't throw an exception). For that reason the entry // can't be put inside a using block. entry.Dispose(); return(content); } catch (Exception ex) { // Remove the worker task from the cache in case it can't complete. tokenSource.Cancel(); // Fail the TCS so other awaiters see the exception. tcs.SetException(ex); throw; } finally { // The tokenSource needs to be disposed as the MemoryCache // will register a callback on the Token. tokenSource.Dispose(); } }
public void Insert(TKey key, TObject obj) { var entry = Cache.CreateEntry(key); entry.SlidingExpiration = TimeSpan.FromMinutes(60); entry.Value = obj; entry.Dispose(); }
public void CreateEntryTest() { IMemoryCache cache = new MemoryCache(new MemoryCacheOptions()); var entry = cache.CreateEntry(1); Assert.Equal(1, entry.Key); }
public static DbGuild AddToCache(DbGuild guild) { RemoveCached(guild.GuildId); return((DbGuild)MemoryCache.CreateEntry(guild.GuildId) .SetValue(guild) .SetAbsoluteExpiration(TimeSpan.FromHours(2)) .SetSlidingExpiration(TimeSpan.FromHours(1)).Value); }
public async Task SetAsync(object key, object entry) { await Task.Run(() => { var a = _cache.CreateEntry(key); _cache.Set(key, entry); }); }
public void LimitTest1() { IMemoryCache cache = new MemoryCache( new MemoryCacheOptions() { EntriesSizeLimit = 3, }); cache.CreateEntry(1).SetPriority(CacheItemPriority.NeverRemove); cache.CreateEntry(2).SetPriority(CacheItemPriority.Low); cache.CreateEntry(3).SetPriority(CacheItemPriority.Normal); cache.CreateEntry(4).SetPriority(CacheItemPriority.Normal); Assert.False(cache.ContainsKey(2)); Assert.True(cache.ContainsKey(1)); Assert.True(cache.ContainsKey(3)); Assert.True(cache.ContainsKey(4)); Assert.True(cache.TrySet(5, new CacheEntry(5))); }
/// <summary> /// Gets the parameter meta data. /// </summary> /// <param name="nodeKey">The node key.</param> /// <param name="metaKey">The meta key.</param> /// <returns></returns> public static string GetParameterMetaData(string nodeKey, string metaKey, string vechileType) { lock (_cache) { var ans = _cache.Get(nodeKey + metaKey + vechileType) as string; if (ans != null) { return(ans); } } if (vechileType == "PX4") { return(ParameterMetaDataRepositoryPX4.GetParameterMetaData(nodeKey, metaKey, vechileType)); } else { var answer = ParameterMetaDataRepositoryAPMpdef.GetParameterMetaData(nodeKey, metaKey, vechileType); if (answer == string.Empty) { answer = ParameterMetaDataRepositoryAPMpdef.GetParameterMetaData(nodeKey, metaKey, "SITL"); } if (answer == string.Empty) { answer = ParameterMetaDataRepositoryAPMpdef.GetParameterMetaData(nodeKey, metaKey, "AP_Periph"); } // add fallback if (answer == string.Empty) { answer = ParameterMetaDataRepositoryAPM.GetParameterMetaData(nodeKey, metaKey, vechileType); } if (answer == string.Empty) { return(String.Empty); } lock (_cache) { try { var ci = _cache.CreateEntry(nodeKey + metaKey + vechileType); ci.Value = answer; ci.Size = ((string)ci.Value).Length; // evict after no access ci.SlidingExpiration = TimeSpan.FromMinutes(5); ci.Dispose(); } catch { } } return(answer); } }
private static void AddToCache(geotiffdata geotiffdata, int x, byte[] scanline) { lock (cachescanlines) { var ci = cachescanlines.CreateEntry(geotiffdata.FileName + x.ToString()); ci.Value = scanline; ci.Size = ((byte[])ci.Value).Length; // evict after no access ci.SlidingExpiration = TimeSpan.FromMinutes(5); ci.Dispose(); } }
/// <summary> /// Cache a player to access it from memory /// </summary> /// <param name="player"></param> public void CachePlayer(Player player) { try { var playerEntry = _playerCache.CreateEntry(player.Home.Id); playerEntry.Value = player; _playerCache.Set(player.Home.Id, playerEntry, _expirationTimeSpan); } catch (Exception) { Logger.Log("Failed to cache player.", GetType(), ErrorLevel.Error); } }
public void CacheAlliance(Alliance alliance) { try { var allianceEntry = _allianceCache.CreateEntry(alliance.Id); allianceEntry.Value = alliance; _allianceCache.Set(alliance.Id, allianceEntry, _expirationTimeSpan); } catch (Exception) { Logger.Log("Failed to cache player.", GetType(), Logger.ErrorLevel.Error); } }
public void RemoveTest() { IMemoryCache cache = new MemoryCache(new MemoryCacheOptions()); var entry = cache.CreateEntry(1); entry.Value = new object(); cache.Remove(1); var result = cache.TryGetValue(1, out var value); Assert.False(result); Assert.Null(value); }