public void AbsoluteExpirationExpiresInBackground() { var clock = new TestClock(); var cache = CreateCache(clock); var key = "myKey"; var value = new object(); var callbackInvoked = new ManualResetEvent(false); var options = new MemoryCacheEntryOptions() .SetAbsoluteExpiration(clock.UtcNow + TimeSpan.FromMinutes(1)) .RegisterPostEvictionCallback((subkey, subValue, reason, state) => { // TODO: Verify params var localCallbackInvoked = (ManualResetEvent)state; localCallbackInvoked.Set(); }, callbackInvoked); var result = cache.Set(key, value, options); Assert.Same(value, result); var found = cache.TryGetValue(key, out result); Assert.True(found); Assert.Same(value, result); clock.Add(TimeSpan.FromMinutes(2)); var ignored = cache.Get("otherKey"); // Background expiration checks are triggered by misc cache activity. Assert.True(callbackInvoked.WaitOne(100), "Callback"); found = cache.TryGetValue(key, out result); Assert.False(found); Assert.Null(result); }
public static void Main(string[] args) { // Runs several concurrent threads that access an item that periodically expires and is re-created. MemoryCache cache = new MemoryCache(new MemoryCacheOptions()); string key = "MyKey"; var options = new MemoryCacheEntryOptions().SetAbsoluteExpiration(TimeSpan.FromMilliseconds(50)); var tasks = new List<Task>(); for (int threads = 0; threads < 100; threads++) { var task = Task.Run(() => { for (int i = 0; i < 110000; i++) { object value; if(!cache.TryGetValue(key, out value)) { // Fake expensive object creation. for (int j = 0; j < 1000000; j++) { } cache.Set(key, new object(), options); } } }); tasks.Add(task); } Console.WriteLine("Running"); Task.WaitAll(tasks.ToArray()); Console.WriteLine("Done"); }
public void RemoveAndReAddFromCallbackWorks() { var cache = CreateCache(); var value = new object(); var obj2 = new object(); string key = "myKey"; var callbackInvoked = new ManualResetEvent(false); var options = new MemoryCacheEntryOptions(); options.PostEvictionCallbacks.Add(new PostEvictionCallbackRegistration() { EvictionCallback = (subkey, subValue, reason, state) => { Assert.Equal(key, subkey); Assert.Same(subValue, value); Assert.Equal(EvictionReason.Removed, reason); var localCallbackInvoked = (ManualResetEvent)state; cache.Set(key, obj2); localCallbackInvoked.Set(); }, State = callbackInvoked }); var result = cache.Set(key, value, options); Assert.Same(value, result); cache.Remove(key); Assert.True(callbackInvoked.WaitOne(100), "Callback"); result = cache.Get(key); Assert.Same(obj2, result); }
/// <inheritdoc /> public ChunkTree GetOrAdd( string pagePath, Func<IFileInfo, ChunkTree> getChunkTree) { if (pagePath == null) { throw new ArgumentNullException(nameof(pagePath)); } if (getChunkTree == null) { throw new ArgumentNullException(nameof(getChunkTree)); } ChunkTree chunkTree; if (!_chunkTreeCache.TryGetValue(pagePath, out chunkTree)) { // GetOrAdd is invoked for each _ViewImport that might potentially exist in the path. // We can avoid performing file system lookups for files that do not exist by caching // negative results and adding a Watch for that file. var options = new MemoryCacheEntryOptions() .AddExpirationToken(_fileProvider.Watch(pagePath)) .SetSlidingExpiration(SlidingExpirationDuration); var file = _fileProvider.GetFileInfo(pagePath); chunkTree = file.Exists ? getChunkTree(file) : null; _chunkTreeCache.Set(pagePath, chunkTree, options); } return chunkTree; }
public void Set([NotNull] string key, byte[] value, DistributedCacheEntryOptions options) { var memoryCacheEntryOptions = new MemoryCacheEntryOptions(); memoryCacheEntryOptions.AbsoluteExpiration = options.AbsoluteExpiration; memoryCacheEntryOptions.AbsoluteExpirationRelativeToNow = options.AbsoluteExpirationRelativeToNow; memoryCacheEntryOptions.SlidingExpiration = options.SlidingExpiration; _memCache.Set(key, value, memoryCacheEntryOptions); }
internal CacheEntry( string key, object value, DateTimeOffset utcNow, DateTimeOffset? absoluteExpiration, MemoryCacheEntryOptions options, Action<CacheEntry> notifyCacheOfExpiration) { Key = key; Value = value; LastAccessed = utcNow; Options = options; _notifyCacheOfExpiration = notifyCacheOfExpiration; _absoluteExpiration = absoluteExpiration; PostEvictionCallbacks = options.PostEvictionCallbacks; }
public void Main() { _cacheEntryOptions = GetCacheEntryOptions(); IMemoryCache cache = new MemoryCache(new MemoryCacheOptions()); SetKey(cache, "0"); PriodicallyReadKey(cache, TimeSpan.FromSeconds(1)); PeriodciallyRemoveKey(cache, TimeSpan.FromSeconds(11)); PeriodciallySetKey(cache, TimeSpan.FromSeconds(13)); Console.ReadLine(); Console.WriteLine("Shutting down"); }
public LocalCacheService() { BucketOptions = new MemoryCacheEntryOptions { Priority = CacheItemPriority.High, PostEvictionCallbacks = { new PostEvictionCallbackRegistration {EvictionCallback = PostEvictionCallback, State = this} }, }; TailOptions = new MemoryCacheEntryOptions { Priority = CacheItemPriority.Low, PostEvictionCallbacks = { new PostEvictionCallbackRegistration {EvictionCallback = PostEvictionCallback, State = this} } }; }
protected object Get(ICacheKey key) { try { _lock.EnterUpgradeableReadLock(); object value; if(cache.TryGetValue(key.GetStringKey(), out value)) { return value; } OnMiss(key, out value); var cacheKey = BuildUniqueStringKey(key); var opts = new MemoryCacheEntryOptions(); if (_useAbsoluteExpiration) { opts.AbsoluteExpiration = AbsoluteExpiration; } else if (_useSlidingExpiration) { opts.SlidingExpiration = SlidingExpirationSpan; } cache.Set(key.GetStringKey(), value, opts); return value; } finally { if(_lock.IsUpgradeableReadLockHeld) { _lock.ExitUpgradeableReadLock(); } } }
/// <inheritdoc /> public CompilerCacheResult GetOrAdd( [NotNull] string relativePath, [NotNull] Func<RelativeFileInfo, CompilationResult> compile) { var normalizedPath = NormalizePath(relativePath); CompilerCacheResult cacheResult; if (!_cache.TryGetValue(normalizedPath, out cacheResult)) { var fileInfo = _fileProvider.GetFileInfo(relativePath); MemoryCacheEntryOptions cacheEntryOptions; CompilerCacheResult cacheResultToCache; if (!fileInfo.Exists) { cacheResultToCache = CompilerCacheResult.FileNotFound; cacheResult = CompilerCacheResult.FileNotFound; cacheEntryOptions = new MemoryCacheEntryOptions(); cacheEntryOptions.AddExpirationTrigger(_fileProvider.Watch(relativePath)); } else { var relativeFileInfo = new RelativeFileInfo(fileInfo, relativePath); var compilationResult = compile(relativeFileInfo).EnsureSuccessful(); cacheEntryOptions = GetMemoryCacheEntryOptions(relativePath); // By default the CompilationResult returned by IRoslynCompiler is an instance of // UncachedCompilationResult. This type has the generated code as a string property and do not want // to cache it. We'll instead cache the unwrapped result. cacheResultToCache = new CompilerCacheResult( CompilationResult.Successful(compilationResult.CompiledType)); cacheResult = new CompilerCacheResult(compilationResult); } _cache.Set(normalizedPath, cacheResultToCache, cacheEntryOptions); } return cacheResult; }
/// <inheritdoc /> public CodeTree GetOrAdd([NotNull] string pagePath, [NotNull] Func<IFileInfo, CodeTree> getCodeTree) { CodeTree codeTree; if (!_codeTreeCache.TryGetValue(pagePath, out codeTree)) { // GetOrAdd is invoked for each _GlobalImport that might potentially exist in the path. // We can avoid performing file system lookups for files that do not exist by caching // negative results and adding a Watch for that file. var options = new MemoryCacheEntryOptions() .AddExpirationTrigger(_fileProvider.Watch(pagePath)) .SetSlidingExpiration(SlidingExpirationDuration); var file = _fileProvider.GetFileInfo(pagePath); codeTree = file.Exists ? getCodeTree(file) : null; _codeTreeCache.Set(pagePath, codeTree, options); } return codeTree; }
public CacheInterceptor(InterceptDelegate next, IMemoryCache cache, IOptions <MemoryCacheEntryOptions> optionsAccessor) { _next = next; _cache = cache; _options = optionsAccessor.Value; }
public void UpdateAllMatches(List <Match> matches) { var cacheEntryoption = new MemoryCacheEntryOptions().SetAbsoluteExpiration(DateTimeOffset.Now.AddMinutes(6)); _cache.Set("matches", matches, cacheEntryoption); }
public UserManagerServicePipeline(IMemoryCache cache) { Cache = cache; MemoryCacheEntryOptions = new MemoryCacheEntryOptions(); }
public void Main() { IMemoryCache cache = new MemoryCache(new MemoryCacheOptions()); object result; string key = "Key"; object newObject = new object(); object state = new object(); // Basic CRUD operations: // Create / Overwrite result = cache.Set(key, newObject); result = cache.Set(key, new object()); // Retrieve, null if not found result = cache.Get(key); // Retrieve bool found = cache.TryGetValue(key, out result); // Delete cache.Remove(key); // Cache entry configuration: // Stays in the cache as long as possible result = cache.Set( key, new object(), new MemoryCacheEntryOptions().SetPriority(CacheItemPriority.NeverRemove)); // Automatically remove if not accessed in the given time result = cache.Set( key, new object(), new MemoryCacheEntryOptions().SetSlidingExpiration(TimeSpan.FromMinutes(5))); // Automatically remove at a certain time result = cache.Set( key, new object(), new MemoryCacheEntryOptions().SetAbsoluteExpiration(DateTimeOffset.UtcNow.AddDays(2))); // Automatically remove at a certain time, which is relative to UTC now result = cache.Set( key, new object(), new MemoryCacheEntryOptions().SetAbsoluteExpiration(relative: TimeSpan.FromMinutes(10))); // Automatically remove if not accessed in the given time // Automatically remove at a certain time (if it lives that long) result = cache.Set( key, new object(), new MemoryCacheEntryOptions() .SetSlidingExpiration(TimeSpan.FromMinutes(5)) .SetAbsoluteExpiration(DateTimeOffset.UtcNow.AddDays(2))); // Callback when evicted var options = new MemoryCacheEntryOptions() .RegisterPostEvictionCallback( (echoKey, value, reason, substate) => { Console.WriteLine(echoKey + ": '" + value + "' was evicted due to " + reason); }); result = cache.Set(key, new object(), options); // Remove on token expiration var cts = new CancellationTokenSource(); options = new MemoryCacheEntryOptions() .AddExpirationToken(new CancellationChangeToken(cts.Token)) .RegisterPostEvictionCallback( (echoKey, value, reason, substate) => { Console.WriteLine(echoKey + ": '" + value + "' was evicted due to " + reason); }); result = cache.Set(key, new object(), options); // Fire the token to see the registered callback being invoked cts.Cancel(); // Expire an entry if the dependent entry expires using (var link = cache.CreateLinkingScope()) { cts = new CancellationTokenSource(); cache.Set("key1", "value1", new MemoryCacheEntryOptions() .AddExpirationToken(new CancellationChangeToken(cts.Token))); // expire this entry if the entry with key "key1" expires. cache.Set("key2", "value2", new MemoryCacheEntryOptions() .AddEntryLink(link) .RegisterPostEvictionCallback( (echoKey, value, reason, substate) => { Console.WriteLine(echoKey + ": '" + value + "' was evicted due to " + reason); })); } // Fire the token to see the registered callback being invoked cts.Cancel(); }
public void SaveDataToCache(int zipCode, string results) { var cacheEntryOptions = new MemoryCacheEntryOptions().SetAbsoluteExpiration(TimeSpan.FromSeconds(_cacheSettings.CacheExpirationSeconds)); _cache.Set(zipCode, results, cacheEntryOptions); }
/// <summary> /// 使用自定义的 options 存进缓存 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="key"></param> /// <param name="value"></param> /// <param name="options"></param> /// <returns></returns> public static T Set <T>(object key, T value, MemoryCacheEntryOptions options) => MemoryCache.Set(key, value, options);
internal static void AddIdentityToCache(Guid userId, ErpIdentity identity) { var options = new MemoryCacheEntryOptions(); options.SetAbsoluteExpiration(TimeSpan.FromMinutes(5)); cache.Set( userId.ToString(), identity, options); // from bet4 to beta5 changed //context => //{ // context.SetAbsoluteExpiration(TimeSpan.FromMinutes(5)); // return identity; //}); }
public JArray GetSoftwares(string name = "", string ver = "", string man = "_unknown", string customerid = "") { JArray jResult = new JArray(); //Try to get value from Memory if (_cache.TryGetValue("mnv-" + man + name + ver, out jResult)) { UpdateURLs(ref jResult); return(jResult); } string sRepository = Settings["repository"]; string lookupPath = Path.Combine(sRepository, "customers", customerid, Base.clean(man.ToLower()), Base.clean(name.ToLower()), Base.clean(ver.ToLower())); if (Directory.Exists(lookupPath)) { foreach (string sFile in Directory.GetFiles(lookupPath, "*.json")) { string sJson = File.ReadAllText(sFile); try { jResult = JArray.Parse(sJson); //fix PreRequisite issue on client when parsing json with null value prerequisite foreach (JObject jObj in jResult) { JToken jPreReq; if (jObj.TryGetValue("PreRequisites", out jPreReq)) { if (string.IsNullOrEmpty(jPreReq.ToString())) { jObj["PreRequisites"] = new JArray(); } } } var cacheEntryOptions = new MemoryCacheEntryOptions().SetSlidingExpiration(TimeSpan.FromSeconds(SlidingExpiration)); //cache hash for x Seconds _cache.Set("mnv-" + man + name + ver, jResult, cacheEntryOptions); UpdateURLs(ref jResult); return(jResult); } catch { } try { jResult = new JArray(); JObject oObj = JObject.Parse(sJson); //fix PreRequisite issue on client when parsing json with null value prerequisite JToken jPreReq; if (oObj.TryGetValue("PreRequisites", out jPreReq)) { if (string.IsNullOrEmpty(jPreReq.ToString())) { oObj["PreRequisites"] = new JArray(); } } jResult.Add(oObj); var cacheEntryOptions = new MemoryCacheEntryOptions().SetSlidingExpiration(TimeSpan.FromSeconds(SlidingExpiration)); //cache hash for x Seconds _cache.Set("mnv-" + man + name + ver, jResult, cacheEntryOptions); UpdateURLs(ref jResult); return(jResult); } catch { } } } lookupPath = Path.Combine(sRepository, Base.clean(man.ToLower()), Base.clean(name.ToLower()), Base.clean(ver.ToLower())); if (Directory.Exists(lookupPath)) { foreach (string sFile in Directory.GetFiles(lookupPath, "*.json")) { string sJson = File.ReadAllText(sFile); try { jResult = JArray.Parse(sJson); //fix PreRequisite issue on client when parsing json with null value prerequisite foreach (JObject jObj in jResult) { JToken jPreReq; if (jObj.TryGetValue("PreRequisites", out jPreReq)) { if (string.IsNullOrEmpty(jPreReq.ToString())) { jObj["PreRequisites"] = new JArray(); } } } var cacheEntryOptions = new MemoryCacheEntryOptions().SetSlidingExpiration(TimeSpan.FromSeconds(SlidingExpiration)); //cache hash for x Seconds _cache.Set("mnv-" + man + name + ver, jResult, cacheEntryOptions); UpdateURLs(ref jResult); return(jResult); } catch { } try { jResult = new JArray(); JObject oObj = JObject.Parse(sJson); //fix PreRequisite issue on client when parsing json with null value prerequisite JToken jPreReq; if (oObj.TryGetValue("PreRequisites", out jPreReq)) { if (string.IsNullOrEmpty(jPreReq.ToString())) { oObj["PreRequisites"] = new JArray(); } } jResult.Add(oObj); var cacheEntryOptions = new MemoryCacheEntryOptions().SetSlidingExpiration(TimeSpan.FromSeconds(SlidingExpiration)); //cache hash for x Seconds _cache.Set("mnv-" + man + name + ver, jResult, cacheEntryOptions); UpdateURLs(ref jResult); return(jResult); } catch { } } } return(new JArray()); }
public void Set(string key, byte[] value, DistributedCacheEntryOptions options) { if (key == null) { throw new ArgumentNullException(nameof(key)); } var memoryCacheEntryOptions = new MemoryCacheEntryOptions(); memoryCacheEntryOptions.AbsoluteExpiration = options.AbsoluteExpiration; memoryCacheEntryOptions.AbsoluteExpirationRelativeToNow = options.AbsoluteExpirationRelativeToNow; memoryCacheEntryOptions.SlidingExpiration = options.SlidingExpiration; _memCache.Set(key, value, memoryCacheEntryOptions); }
public object Set(object key, object value, MemoryCacheEntryOptions cacheEntryOptions) { if (key == null) { throw new ArgumentNullException(nameof(key)); } CheckDisposed(); CacheEntry priorEntry = null; var utcNow = _clock.UtcNow; DateTimeOffset? absoluteExpiration = null; if (cacheEntryOptions.AbsoluteExpirationRelativeToNow.HasValue) { absoluteExpiration = utcNow + cacheEntryOptions.AbsoluteExpirationRelativeToNow; } else if (cacheEntryOptions.AbsoluteExpiration.HasValue) { if (cacheEntryOptions.AbsoluteExpiration <= utcNow) { throw new ArgumentOutOfRangeException( nameof(MemoryCacheEntryOptions.AbsoluteExpiration), cacheEntryOptions.AbsoluteExpiration.Value, "The absolute expiration value must be in the future."); } absoluteExpiration = cacheEntryOptions.AbsoluteExpiration; } var entry = new CacheEntry( key, value, utcNow, absoluteExpiration, cacheEntryOptions, _entryExpirationNotification); var link = EntryLinkHelpers.ContextLink; if (link != null) { // Copy expiration tokens and AbsoluteExpiration to the link. // We do this regardless of it gets cached because the tokens are associated with the value we'll return. if (entry.Options.ExpirationTokens != null) { link.AddExpirationTokens(entry.Options.ExpirationTokens); } if (absoluteExpiration.HasValue) { link.SetAbsoluteExpiration(absoluteExpiration.Value); } } bool added = false; _entryLock.EnterWriteLock(); try { if (_entries.TryGetValue(key, out priorEntry)) { _entries.Remove(key); priorEntry.SetExpired(EvictionReason.Replaced); } if (!entry.CheckExpired(utcNow)) { _entries[key] = entry; entry.AttachTokens(); added = true; } } finally { _entryLock.ExitWriteLock(); } if (priorEntry != null) { priorEntry.InvokeEvictionCallbacks(); } if (!added) { entry.InvokeEvictionCallbacks(); } StartScanForExpiredItems(); return value; }
/// <summary> /// Adds version query parameter to the specified file path. /// </summary> /// <param name="path">The path of the file to which version should be added.</param> /// <returns>Path containing the version query string.</returns> /// <remarks> /// The version query string is appended as with the key "v". /// </remarks> public string AddFileVersionToPath(string path) { if (path == null) { throw new ArgumentNullException(nameof(path)); } var resolvedPath = path; var queryStringOrFragmentStartIndex = path.IndexOfAny(new char[] { '?', '#' }); if (queryStringOrFragmentStartIndex != -1) { resolvedPath = path.Substring(0, queryStringOrFragmentStartIndex); } Uri uri; if (Uri.TryCreate(resolvedPath, UriKind.Absolute, out uri) && !uri.IsFile) { // Don't append version if the path is absolute. return path; } var fileInfo = _fileProvider.GetFileInfo(resolvedPath); if (!fileInfo.Exists) { if (_requestPathBase.HasValue && resolvedPath.StartsWith(_requestPathBase.Value, StringComparison.OrdinalIgnoreCase)) { resolvedPath = resolvedPath.Substring(_requestPathBase.Value.Length); fileInfo = _fileProvider.GetFileInfo(resolvedPath); } if (!fileInfo.Exists) { // if the file is not in the current server. return path; } } string value; if (!_cache.TryGetValue(path, out value)) { value = QueryHelpers.AddQueryString(path, VersionKey, GetHashForFile(fileInfo)); var cacheEntryOptions = new MemoryCacheEntryOptions().AddExpirationToken(_fileProvider.Watch(resolvedPath)); _cache.Set(path, value, cacheEntryOptions); } return value; }
public void SetOverwritesAndInvokesCallbacks() { var cache = CreateCache(); var value1 = new object(); string key = "myKey"; var callback1Invoked = new ManualResetEvent(false); var callback2Invoked = new ManualResetEvent(false); var options1 = new MemoryCacheEntryOptions(); options1.PostEvictionCallbacks.Add(new PostEvictionCallbackRegistration() { EvictionCallback = (subkey, subValue, reason, state) => { Assert.Equal(key, subkey); Assert.Same(subValue, value1); Assert.Equal(EvictionReason.Replaced, reason); var localCallbackInvoked = (ManualResetEvent)state; localCallbackInvoked.Set(); }, State = callback1Invoked }); var result = cache.Set(key, value1, options1); Assert.Same(value1, result); var value2 = new object(); var options2 = new MemoryCacheEntryOptions(); options2.PostEvictionCallbacks.Add(new PostEvictionCallbackRegistration() { EvictionCallback = (subkey, subValue, reason, state) => { // Shouldn't be invoked. var localCallbackInvoked = (ManualResetEvent)state; localCallbackInvoked.Set(); }, State = callback2Invoked }); result = cache.Set(key, value2, options2); Assert.Same(value2, result); Assert.True(callback1Invoked.WaitOne(100), "Callback1"); Assert.False(callback2Invoked.WaitOne(0), "Callback2"); result = cache.Get(key); Assert.Same(value2, result); Assert.False(callback2Invoked.WaitOne(0), "Callback2"); }
internal static void AddIdentityToCache(Guid userId, ErpIdentity identity) { var options = new MemoryCacheEntryOptions(); options.SetAbsoluteExpiration(TimeSpan.FromMinutes(5)); cache.Set(userId.ToString(), identity, options); }
public void Set(string key, object item, MemoryCacheEntryOptions policy) { }
public async Task <LocalRedirectResult> Callback([FromQuery] string code, [FromQuery] string state) { string _access_token; string _token_type; string _scope; int _expires_in; string _refresh_token; var SpotifyServicesConfiguration = _configuration.GetSection("SpotifyServices") .Get <SpotifyServicesConfigurations>(); var redirect_uri = SpotifyServicesConfiguration.RedirectUri; var client_id = SpotifyServicesConfiguration.ClientId; var client_secret = SpotifyServicesConfiguration.ClientSecret; var request = new HttpRequestMessage(HttpMethod.Post, SpotifyServicesConfiguration.AuthorizeAPIBaseURI + "/api/token"); var client = _clientFactory.CreateClient(); var RequestBody = new Dictionary <string, string>(); RequestBody.Add("grant_type", "authorization_code"); RequestBody.Add("code", code); RequestBody.Add("redirect_uri", redirect_uri); request.Content = new FormUrlEncodedContent(RequestBody); var Credentials = client_id + ":" + client_secret; byte[] data = System.Text.ASCIIEncoding.ASCII.GetBytes(Credentials); var base64EncodedCredentials = System.Convert.ToBase64String(data); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", base64EncodedCredentials); var response = await client.SendAsync(request); var content = await response.Content.ReadAsStringAsync(); var _spotifyservicesapitoken = JsonSerializer.Deserialize <SpotifyServicesAPIToken>(content); if (!_cache.TryGetValue(SpotifyServicesAPITokenCache.access_token, out _access_token)) { _access_token = _spotifyservicesapitoken.access_token; var cacheEntryOptions = new MemoryCacheEntryOptions(); _cache.Set(SpotifyServicesAPITokenCache.access_token, _access_token, cacheEntryOptions); } if (!_cache.TryGetValue(SpotifyServicesAPITokenCache.token_type, out _token_type)) { _token_type = _spotifyservicesapitoken.token_type; var cacheEntryOptions = new MemoryCacheEntryOptions(); _cache.Set(SpotifyServicesAPITokenCache.token_type, _token_type, cacheEntryOptions); } if (!_cache.TryGetValue(SpotifyServicesAPITokenCache.scope, out _scope)) { _scope = _spotifyservicesapitoken.scope; var cacheEntryOptions = new MemoryCacheEntryOptions(); _cache.Set(SpotifyServicesAPITokenCache.scope, _scope, cacheEntryOptions); } if (!_cache.TryGetValue(SpotifyServicesAPITokenCache.expires_in, out _expires_in)) { _expires_in = _spotifyservicesapitoken.expires_in; var cacheEntryOptions = new MemoryCacheEntryOptions(); _cache.Set(SpotifyServicesAPITokenCache.expires_in, _expires_in, cacheEntryOptions); } if (!_cache.TryGetValue(SpotifyServicesAPITokenCache.refresh_token, out _refresh_token)) { _refresh_token = _spotifyservicesapitoken.refresh_token; var cacheEntryOptions = new MemoryCacheEntryOptions(); _cache.Set(SpotifyServicesAPITokenCache.refresh_token, _refresh_token, cacheEntryOptions); } return(LocalRedirect("/MusicPage")); }
public JArray GetSoftwares(string shortname, string customerid = "") { JArray jResult = new JArray(); //Try to get value from Memory if (_cache.TryGetValue("sn-" + shortname, out jResult)) { UpdateURLs(ref jResult); return(jResult); } string sRepository = Settings["repository"]; if (!File.Exists(Path.Combine(sRepository, Base.clean(shortname.ToLower()) + ".json"))) { return(new JArray()); } string sJson = File.ReadAllText(Path.Combine(sRepository, Base.clean(shortname.ToLower()) + ".json")); try { if (sJson.TrimStart().StartsWith("[")) { jResult = JArray.Parse(sJson); } else { JObject jObj = JObject.Parse(sJson); jResult = new JArray(); jResult.Add(jObj); } //fix PreRequisite issue on client when parsing json with null value prerequisite foreach (JObject jObj in jResult) { JToken jPreReq; if (jObj.TryGetValue("PreRequisites", out jPreReq)) { if (string.IsNullOrEmpty(jPreReq.ToString())) { jObj["PreRequisites"] = new JArray(); } } } var cacheEntryOptions = new MemoryCacheEntryOptions().SetSlidingExpiration(TimeSpan.FromSeconds(SlidingExpiration)); //cache hash for x Seconds _cache.Set("sn-" + shortname, jResult, cacheEntryOptions); UpdateURLs(ref jResult); return(jResult); } catch { } try { jResult = new JArray(); JObject oObj = JObject.Parse(sJson); //fix PreRequisite issue on client when parsing json with null value prerequisite JToken jPreReq; if (oObj.TryGetValue("PreRequisites", out jPreReq)) { if (string.IsNullOrEmpty(jPreReq.ToString())) { oObj["PreRequisites"] = new JArray(); } } jResult.Add(oObj); var cacheEntryOptions = new MemoryCacheEntryOptions().SetSlidingExpiration(TimeSpan.FromSeconds(SlidingExpiration)); //cache hash for x Seconds _cache.Set("sn-" + shortname, jResult, cacheEntryOptions); UpdateURLs(ref jResult); return(jResult); } catch { } return(new JArray()); }
public static Func <T1, T2, T3, TResult> Create <T1, T2, T3, TResult>(Func <T1, T2, T3, TResult> func, MemoryCacheEntryOptions options) { return(Create(func, DefaultCache ?? throw new InvalidOperationException("Memoization.DefaultCache is null"), options)); }
public async Task ProcessAsync_FlowsEntryLinkThatAllowsAddingTriggersToAddedEntry() { // Arrange var id = "some-id"; var expectedContent = new DefaultTagHelperContent(); expectedContent.SetContent("some-content"); var tokenSource = new CancellationTokenSource(); var cache = new MemoryCache(new MemoryCacheOptions()); var cacheEntryOptions = new MemoryCacheEntryOptions() .AddExpirationTrigger(new CancellationTokenTrigger(tokenSource.Token)); var tagHelperContext = new TagHelperContext( allAttributes: new TagHelperAttributeList(), items: new Dictionary<object, object>(), uniqueId: id, getChildContentAsync: () => { TagHelperContent tagHelperContent; if(!cache.TryGetValue("key1", out tagHelperContent)) { tagHelperContent = expectedContent; cache.Set("key1", tagHelperContent, cacheEntryOptions); } return Task.FromResult(tagHelperContent); }); var tagHelperOutput = new TagHelperOutput("cache", new TagHelperAttributeList { { "attr", "value" } }); tagHelperOutput.PreContent.SetContent("<cache>"); tagHelperOutput.PostContent.SetContent("</cache>"); var cacheTagHelper = new CacheTagHelper(cache) { ViewContext = GetViewContext(), }; var key = cacheTagHelper.GenerateKey(tagHelperContext); // Act - 1 await cacheTagHelper.ProcessAsync(tagHelperContext, tagHelperOutput); TagHelperContent cachedValue; var result = cache.TryGetValue(key, out cachedValue); // Assert - 1 Assert.Equal(expectedContent.GetContent(), tagHelperOutput.Content.GetContent()); Assert.True(result); Assert.Equal(expectedContent, cachedValue); // Act - 2 tokenSource.Cancel(); result = cache.TryGetValue(key, out cachedValue); // Assert - 2 Assert.False(result); Assert.Null(cachedValue); }
private async Task ProcessRequest(HttpContext context, string requestKey, int hitCount, MemoryCacheEntryOptions cacheEntryOptions) { hitCount++; requestStore.Set(requestKey, hitCount, cacheEntryOptions); context.Response.Headers["X-Rate-Limit"] = limit.ToString(); context.Response.Headers["X-Rate-Limit-Remaining"] = (limit - hitCount).ToString(); await next(context); }
public Task <T> GetOrAddAsync <T>(string key, Func <ICacheEntry, Task <T> > addItemFactory, MemoryCacheEntryOptions policy) { return(addItemFactory(new MockCacheEntry(key))); }
public static void SetSliding <T>(this IMemoryCache cache, Object key, T value, Int32 minutesCount) { var cacheEntryOptions = new MemoryCacheEntryOptions().SetSlidingExpiration(TimeSpan.FromMinutes(minutesCount)); cache.Set(key, value, cacheEntryOptions); }
public void Add <T>(string key, T item, MemoryCacheEntryOptions policy) { }
public async Task <CommandResult <Step> > Handle(AssignStepCommand request, CancellationToken cancellationToken) { var stopwatch = new Stopwatch(); stopwatch.Start(); List <Guid> ignoreUnassignedSteps = new List <Guid>(); if (_clusterStateService.GetSettings.AssignmentEnabled) { var assignedStepSuccessfully = false; Step unassignedStep = null; var dateChecked = DateTime.UtcNow; BotKey botkey; if (!_cache.TryGetValue(request.BotId, out botkey)) { // Set cache options. var cacheEntryOptions = new MemoryCacheEntryOptions() // Keep in cache for this time, reset time if accessed. .SetSlidingExpiration(TimeSpan.FromSeconds(10)); botkey = await _entitiesRepository.GetFirstOrDefaultAsync <BotKey>(bk => bk.Id == request.BotId); // Save data in cache. _cache.Set(request.BotId, botkey, cacheEntryOptions); } if (botkey.IsDisabled) { return(new CommandResult <Step>(new BotKeyAssignmentException("Bot " + botkey.Id + " is disabled.")) { Type = CommandResultTypes.Update, ElapsedMs = stopwatch.ElapsedMilliseconds }); } ignoreUnassignedSteps.AddRange(_clusterStateService.GetState().Locks.Where(l => l.Key.Contains("_object")).Select(ol => new Guid(ol.Key.Split(':').Last()))); do { unassignedStep = (await _entitiesRepository.GetAsync <Step>(s => s.Status == StepStatuses.Unassigned && request.StepTemplateIds.Contains(s.StepTemplateId) && !ignoreUnassignedSteps.Contains(s.Id), null, "CreatedOn:1", 1, 0)).FirstOrDefault(); if (unassignedStep != null) { var assigned = await _node.Handle(new RequestDataShard() { Type = unassignedStep.ShardType, ObjectId = unassignedStep.Id, CreateLock = true, LockTimeoutMs = 10000 }); //Apply a lock on the item if (assigned != null && assigned.IsSuccessful && assigned.AppliedLocked) { //Real values to pass to the Microservice Dictionary <string, object> realAssignedValues = new Dictionary <string, object>(); //Inputs that have been converted to reference expression Dictionary <string, object> convertedInputs = new Dictionary <string, object>(); var template = await _entitiesRepository.GetFirstOrDefaultAsync <StepTemplate>(st => st.ReferenceId == unassignedStep.StepTemplateId); try { //This should not throw a error externally, the server should loop to the next one and log a error if (unassignedStep.Status != StepStatuses.Unassigned) { throw new InvalidStepQueueException("You cannot assign step " + unassignedStep.Id + " as it is not unassigned."); } bool inputsUpdated = false; foreach (var input in unassignedStep.Inputs) { string convertedValue = ""; bool isReferenceByValue = false; var isReference = InputDataUtility.IsInputReference(input, out convertedValue, out isReferenceByValue); if (input.Value is string && ((string)input.Value).Length > 1) { if (isReference) { //Copy by reference if (isReferenceByValue) { var foundGlobalValue = await _entitiesRepository.GetFirstOrDefaultAsync <GlobalValue>(gv => gv.Name == convertedValue); if (foundGlobalValue == null) { Logger.LogWarning("No global value was found for value " + input.Value); realAssignedValues.Add(input.Key, null); convertedInputs.Add(input.Key, input.Value + ":?"); } else if (foundGlobalValue.Type != template.InputDefinitions[input.Key].Type) { Logger.LogWarning("Global value was found for value " + input.Value + " however they are different types. " + template.InputDefinitions[input.Key].Type + " vs " + foundGlobalValue.Type); realAssignedValues.Add(input.Key, null); convertedInputs.Add(input.Key, input.Value + ":?"); } else { realAssignedValues.Add(input.Key, foundGlobalValue.Value); convertedInputs.Add(input.Key, input.Value + ":" + foundGlobalValue.Journal.GetCurrentChainId()); } } //copy by value else { var foundGlobalValue = await _entitiesRepository.GetFirstOrDefaultAsync <GlobalValue>(gv => gv.Name == convertedValue); if (foundGlobalValue == null) { Logger.LogWarning("No global value was found for value " + input.Value); realAssignedValues.Add(input.Key, null); convertedInputs.Add(input.Key, null); } else if (foundGlobalValue.Type != template.InputDefinitions[input.Key].Type) { Logger.LogWarning("Global value was found for value " + input.Value + " however they are different types. " + template.InputDefinitions[input.Key].Type + " vs " + foundGlobalValue.Type); realAssignedValues.Add(input.Key, null); convertedInputs.Add(input.Key, null); } else { realAssignedValues.Add(input.Key, foundGlobalValue.Value); convertedInputs.Add(input.Key, foundGlobalValue.Value); } } inputsUpdated = true; } else if (input.Value is string && ((string)input.Value).Length > 1 && ((string)input.Value).First() == '\\') { var escapedCommand = ((string)input.Value); //The $ is escaped realAssignedValues.Add(input.Key, ((string)input.Value).Substring(1, escapedCommand.Length - 1)); convertedInputs.Add(input.Key, input.Value); inputsUpdated = true; } else { realAssignedValues.Add(input.Key, input.Value); convertedInputs.Add(input.Key, input.Value); } } else { realAssignedValues.Add(input.Key, input.Value); convertedInputs.Add(input.Key, input.Value); } } //If a update was detected then add it to the journal updates if (inputsUpdated) { unassignedStep.UpdateJournal(new Domain.Entities.JournalEntries.JournalEntry() { CreatedBy = SystemUsers.QUEUE_MANAGER, CreatedOn = DateTime.UtcNow, Updates = new List <Update>() { new Update() { Type = UpdateType.Override, FieldName = "status", Value = StepStatuses.Assigned }, new Update() { FieldName = "inputs", Type = UpdateType.Override, Value = convertedInputs }, new Update() { FieldName = "assignedto", Type = UpdateType.Override, Value = request.BotId } } }); } else { unassignedStep.UpdateJournal(new Domain.Entities.JournalEntries.JournalEntry() { CreatedBy = SystemUsers.QUEUE_MANAGER, CreatedOn = DateTime.UtcNow, Updates = new List <Update>() { new Update() { Type = UpdateType.Override, FieldName = "status", Value = StepStatuses.Assigned } } }); } await _node.Handle(new AddShardWriteOperation() { Data = unassignedStep, WaitForSafeWrite = true, Operation = ConsensusCore.Domain.Enums.ShardOperationOptions.Update, RemoveLock = true, LockId = assigned.LockId.Value }); //await _entitiesRepository.UpdateStep(unassignedStep); if (inputsUpdated) { //Update the record with real values, this is not commited to DB unassignedStep.UpdateJournal(new Domain.Entities.JournalEntries.JournalEntry() { CreatedBy = SystemUsers.QUEUE_MANAGER, CreatedOn = DateTime.UtcNow, Updates = new List <Update>() { new Update() { FieldName = "inputs", Type = UpdateType.Override, Value = realAssignedValues } } }); } } catch (Exception e) { Console.WriteLine(e.Message); //throw e; } assignedStepSuccessfully = true; } else { ignoreUnassignedSteps.Add(unassignedStep.Id); assignedStepSuccessfully = false; } } //There were no unassigned steps to assign else { assignedStepSuccessfully = true; } }while (!assignedStepSuccessfully); if (unassignedStep != null) { var template = await _entitiesRepository.GetFirstOrDefaultAsync <StepTemplate>(st => st.ReferenceId == unassignedStep.StepTemplateId); //Decrypt the step unassignedStep.Inputs = DynamicDataUtility.DecryptDynamicData(template.InputDefinitions, unassignedStep.Inputs, EncryptionProtocol.AES256, ClusterStateService.GetEncryptionKey()); unassignedStep.RemoveDelimiters(); //Encrypt the step unassignedStep.Inputs = DynamicDataUtility.EncryptDynamicData(template.InputDefinitions, unassignedStep.Inputs, EncryptionProtocol.RSA, botkey.PublicEncryptionKey, true); } stopwatch.Stop(); return(new CommandResult <Step>() { ObjectRefId = unassignedStep != null?unassignedStep.Id.ToString() : "", ElapsedMs = stopwatch.ElapsedMilliseconds, Type = CommandResultTypes.Update, Result = unassignedStep != null ? unassignedStep : null }); } else { return(new CommandResult <Step>() { ObjectRefId = "", ElapsedMs = stopwatch.ElapsedMilliseconds, Type = CommandResultTypes.None }); } }
public void SetCache <T>(string key, T value, MemoryCacheEntryOptions options) where T : class { _cache.Set(key, value, options); }
public CacheManager(IMemoryCache memoryCache) { _memoryCache = memoryCache; memoryCacheEntryOptions = new MemoryCacheEntryOptions { AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(20) }; }
public Task HandleScheduleAsync() { var cacheEntryOptions = new MemoryCacheEntryOptions().SetSlidingExpiration(TimeSpan.FromMinutes(20)); DateTime?lastUpdatedTimeCache; Dictionary <int, ProductViewModel> productsCache; // We keep two cahces: Products and LastUpdatedTime. // If Products Cache is empty; we fill it with all data. And setup LastUpdatedTime Cache with the highest LastUpdatedDate value among products. // If Products Cache is already full; we get products from database which has higher LastUpdatedTime from our cached update time (holding in LastUpdatedTime cache) // Then update Products Cache with the returned products from database. if (!_cache.TryGetValue("Products", out productsCache)) { productsCache = _context.Products .Select(p => new ProductViewModel { Id = p.Id, Name = p.Name, LastUpdatedTime = p.LastUpdatedTime }).ToDictionary(p => p.Id, p => p); _cache.Set("Products", productsCache, cacheEntryOptions); //set LastUpdatedTimeCache lastUpdatedTimeCache = productsCache.Where(p => p.Value.LastUpdatedTime != null)?.Max(p => p.Value.LastUpdatedTime); _cache.Set("LastUpdatedTime", lastUpdatedTimeCache ?? DateTime.Now, cacheEntryOptions); } else { lastUpdatedTimeCache = (DateTime)_cache.Get("LastUpdatedTime"); //return updated products after the last cache update: add null values too List <ProductViewModel> lastUpdatedProducts = _context.Products.Where(p => p.LastUpdatedTime > lastUpdatedTimeCache || p.LastUpdatedTime == null) .Select(p => new ProductViewModel { Id = p.Id, Name = p.Name, LastUpdatedTime = p.LastUpdatedTime }).ToList(); foreach (ProductViewModel updatedProduct in lastUpdatedProducts) { if (productsCache.ContainsKey(updatedProduct.Id)) { productsCache[updatedProduct.Id] = updatedProduct; } else { productsCache.Add(updatedProduct.Id, updatedProduct); } } _cache.Set("Products", productsCache, cacheEntryOptions); //set LastUpdatedTimeCache lastUpdatedTimeCache = productsCache.Where(p => p.Value.LastUpdatedTime != null)?.Max(p => p.Value.LastUpdatedTime); _cache.Set("LastUpdatedTime", lastUpdatedTimeCache ?? DateTime.Now, cacheEntryOptions); } return(Task.CompletedTask); }
public void UpdateMatchByKey(string key, Match match) { var cacheEntryoption = new MemoryCacheEntryOptions().SetAbsoluteExpiration(DateTimeOffset.Now.AddMinutes(6)); _cache.Set(key, match, cacheEntryoption); }
protected void StoreInCache(DnsQuestion dnsQuestionInput, List <DnsRecordBase> data, MemoryCacheEntryOptions cacheEntryOptions) { CacheManager.StoreInCache(dnsQuestionInput, data, cacheEntryOptions); }
public object GetOrCreate <T>(string key, MemoryCacheEntryOptions policy, Func <ICacheEntry, T> func) { return(func(null)); }
/// <summary> /// Return the result of the <paramref name="query" /> from the cache. If the query is not cached /// yet, the query is materialized and cached before being returned. /// </summary> /// <typeparam name="T">The generic type of the query.</typeparam> /// <param name="query">The query to cache in the QueryCacheManager.</param> /// <param name="options">The cache entry options to use to cache the query.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <param name="tags"> /// A variable-length parameters list containing tags to expire cached /// entries. /// </param> /// <returns>The result of the query.</returns> public static Task <T> FromCacheAsync <T>(this QueryDeferred <T> query, MemoryCacheEntryOptions options, params string[] tags) { return(query.FromCacheAsync(options, default(CancellationToken), tags)); }
/// <summary> /// Get or add item to cache /// </summary> /// <typeparam name="T"></typeparam> /// <param name="cache"></param> /// <param name="key"></param> /// <param name="addItemFactory"></param> /// <param name="policy"></param> /// <returns></returns> public static Task <T> GetOrAddAsync <T>(this IAppCache cache, string key, Func <Task <T> > addItemFactory, MemoryCacheEntryOptions policy) { if (cache == null) { throw new ArgumentNullException(nameof(cache)); } return(cache.GetOrAddAsync(key, entry => { entry.SetOptions(policy); return addItemFactory(); })); }
public static Func <T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, TResult> Create <T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, TResult>(Func <T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, TResult> func, IMemoryCache cache, MemoryCacheEntryOptions options) { return((T1 t1, T2 t2, T3 t3, T4 t4, T5 t5, T6 t6, T7 t7, T8 t8, T9 t9, T10 t10, T11 t11, T12 t12, T13 t13, T14 t14, T15 t15, T16 t16) => { var key = (t1, t2, t3, t4, t5, t6, t7, t8, t9, t10, t11, t12, t13, t14, t15, t16); if (!cache.TryGetValue <TResult>(key, out var result)) { var entry = cache.CreateEntry(key); result = func(t1, t2, t3, t4, t5, t6, t7, t8, t9, t10, t11, t12, t13, t14, t15, t16); entry.SetOptions(options); entry.SetValue(result); // need to manually call dispose instead of having a using // in case the factory passed in throws, in which case we // do not want to add the entry to the cache entry.Dispose(); } return result; }); }
private Task <CompiledViewDescriptor> OnCacheMiss(string normalizedPath) { ViewCompilerWorkItem item; TaskCompletionSource <CompiledViewDescriptor> taskSource; MemoryCacheEntryOptions cacheEntryOptions; // Safe races cannot be allowed when compiling Razor pages. To ensure only one compilation request succeeds // per file, we'll lock the creation of a cache entry. Creating the cache entry should be very quick. The // actual work for compiling files happens outside the critical section. lock (_cacheLock) { // Double-checked locking to handle a possible race. if (_cache.TryGetValue(normalizedPath, out Task <CompiledViewDescriptor> result)) { return(result); } if (_precompiledViews.TryGetValue(normalizedPath, out var precompiledView)) { Log.ViewCompilerLocatedCompiledViewForPath(_logger, normalizedPath); item = CreatePrecompiledWorkItem(normalizedPath, precompiledView); } else { item = CreateRuntimeCompilationWorkItem(normalizedPath); } // At this point, we've decided what to do - but we should create the cache entry and // release the lock first. cacheEntryOptions = new MemoryCacheEntryOptions(); Debug.Assert(item.ExpirationTokens != null); for (var i = 0; i < item.ExpirationTokens.Count; i++) { cacheEntryOptions.ExpirationTokens.Add(item.ExpirationTokens[i]); } taskSource = new TaskCompletionSource <CompiledViewDescriptor>(creationOptions: TaskCreationOptions.RunContinuationsAsynchronously); if (item.SupportsCompilation) { // We'll compile in just a sec, be patient. } else { // If we can't compile, we should have already created the descriptor Debug.Assert(item.Descriptor != null); taskSource.SetResult(item.Descriptor); } _cache.Set(normalizedPath, taskSource.Task, cacheEntryOptions); } // Now the lock has been released so we can do more expensive processing. if (item.SupportsCompilation) { Debug.Assert(taskSource != null); if (item.Descriptor?.Item != null && ChecksumValidator.IsItemValid(_projectEngine.FileSystem, item.Descriptor.Item)) { // If the item has checksums to validate, we should also have a precompiled view. Debug.Assert(item.Descriptor != null); taskSource.SetResult(item.Descriptor); return(taskSource.Task); } Log.ViewCompilerInvalidatingCompiledFile(_logger, item.NormalizedPath); try { var descriptor = CompileAndEmit(normalizedPath); descriptor.ExpirationTokens = cacheEntryOptions.ExpirationTokens; taskSource.SetResult(descriptor); } catch (Exception ex) { taskSource.SetException(ex); } } return(taskSource.Task); }
private CompilerCacheResult CreateCacheEntry( string normalizedPath, Func<RelativeFileInfo, CompilationResult> compile) { CompilerCacheResult cacheResult; var fileInfo = _fileProvider.GetFileInfo(normalizedPath); MemoryCacheEntryOptions cacheEntryOptions; CompilerCacheResult cacheResultToCache; if (!fileInfo.Exists) { cacheResultToCache = CompilerCacheResult.FileNotFound; cacheResult = CompilerCacheResult.FileNotFound; cacheEntryOptions = new MemoryCacheEntryOptions(); cacheEntryOptions.AddExpirationToken(_fileProvider.Watch(normalizedPath)); } else { var relativeFileInfo = new RelativeFileInfo(fileInfo, normalizedPath); var compilationResult = compile(relativeFileInfo).EnsureSuccessful(); cacheEntryOptions = GetMemoryCacheEntryOptions(normalizedPath); // By default the CompilationResult returned by IRoslynCompiler is an instance of // UncachedCompilationResult. This type has the generated code as a string property and do not want // to cache it. We'll instead cache the unwrapped result. cacheResultToCache = new CompilerCacheResult( CompilationResult.Successful(compilationResult.CompiledType)); cacheResult = new CompilerCacheResult(compilationResult); } _cache.Set(normalizedPath, cacheResultToCache, cacheEntryOptions); return cacheResult; }
public void Main() { IMemoryCache cache = new MemoryCache(new MemoryCacheOptions()); object result; string key = "Key"; object newObject = new object(); object state = new object(); // Basic CRUD operations: // Create / Overwrite result = cache.Set(key, newObject); result = cache.Set(key, new object()); // Retrieve, null if not found result = cache.Get(key); // Retrieve bool found = cache.TryGetValue(key, out result); // Delete cache.Remove(key); // Cache entry configuration: // Stays in the cache as long as possible result = cache.Set( key, new object(), new MemoryCacheEntryOptions().SetPriority(CacheItemPriority.NeverRemove)); // Automatically remove if not accessed in the given time result = cache.Set( key, new object(), new MemoryCacheEntryOptions().SetSlidingExpiration(TimeSpan.FromMinutes(5))); // Automatically remove at a certain time result = cache.Set( key, new object(), new MemoryCacheEntryOptions().SetAbsoluteExpiration(DateTimeOffset.UtcNow.AddDays(2))); // Automatically remove at a certain time, which is relative to UTC now result = cache.Set( key, new object(), new MemoryCacheEntryOptions().SetAbsoluteExpiration(relative: TimeSpan.FromMinutes(10))); // Automatically remove if not accessed in the given time // Automatically remove at a certain time (if it lives that long) result = cache.Set( key, new object(), new MemoryCacheEntryOptions() .SetSlidingExpiration(TimeSpan.FromMinutes(5)) .SetAbsoluteExpiration(DateTimeOffset.UtcNow.AddDays(2))); // Callback when evicted var options = new MemoryCacheEntryOptions() .RegisterPostEvictionCallback( (echoKey, value, reason, substate) => { Console.WriteLine(echoKey + ": '" + value + "' was evicted due to " + reason); }); result = cache.Set(key, new object(), options); // Remove on token expiration var cts = new CancellationTokenSource(); options = new MemoryCacheEntryOptions() .AddExpirationToken(new CancellationChangeToken(cts.Token)) .RegisterPostEvictionCallback( (echoKey, value, reason, substate) => { Console.WriteLine(echoKey + ": '" + value + "' was evicted due to " + reason); }); result = cache.Set(key, new object(), options); // Fire the token to see the registered callback being invoked cts.Cancel(); // Expire an entry if the dependent entry expires using (var link = cache.CreateLinkingScope()) { cts = new CancellationTokenSource(); cache.Set("key1", "value1", new MemoryCacheEntryOptions() .AddExpirationToken(new CancellationChangeToken(cts.Token))); // expire this entry if the entry with key "key1" expires. cache.Set("key2", "value2", new MemoryCacheEntryOptions() .AddEntryLink(link) .RegisterPostEvictionCallback( (echoKey, value, reason, substate) => { Console.WriteLine(echoKey + ": '" + value + "' was evicted due to " + reason); })); } // Fire the token to see the registered callback being invoked cts.Cancel(); }
public string AddFileVersionToPath(PathString requestPathBase, string path) { if (path == null) { throw new ArgumentNullException(nameof(path)); } var resolvedPath = path; var queryStringOrFragmentStartIndex = path.IndexOfAny(QueryStringAndFragmentTokens); if (queryStringOrFragmentStartIndex != -1) { resolvedPath = path.Substring(0, queryStringOrFragmentStartIndex); } if (Uri.TryCreate(resolvedPath, UriKind.Absolute, out var uri) && !uri.IsFile) { // Don't append version if the path is absolute. return(path); } // Try to get the hash from the tenant level cache. if (_cache.TryGetValue(resolvedPath, out string value)) { if (value.Length > 0) { return(QueryHelpers.AddQueryString(path, VersionKey, value)); } return(path); } // Try to get the hash from the cache shared accross tenants. if (resolvedPath.StartsWith(requestPathBase.Value, StringComparison.OrdinalIgnoreCase)) { if (_sharedCache.TryGetValue(resolvedPath.Substring(requestPathBase.Value.Length), out value)) { return(QueryHelpers.AddQueryString(path, VersionKey, value)); } } var cacheKey = resolvedPath; var cacheEntryOptions = new MemoryCacheEntryOptions(); foreach (var fileProvider in _fileProviders) { cacheEntryOptions.AddExpirationToken(fileProvider.Watch(resolvedPath)); var fileInfo = fileProvider.GetFileInfo(resolvedPath); // Perform check against requestPathBase. if (!fileInfo.Exists && requestPathBase.HasValue && resolvedPath.StartsWith(requestPathBase.Value, StringComparison.OrdinalIgnoreCase)) { resolvedPath = resolvedPath.Substring(requestPathBase.Value.Length); cacheEntryOptions.AddExpirationToken(fileProvider.Watch(resolvedPath)); fileInfo = fileProvider.GetFileInfo(resolvedPath); } // Perform check against VirtualPathBase. if (!fileInfo.Exists && fileProvider is IVirtualPathBaseProvider virtualPathBaseProvider && virtualPathBaseProvider.VirtualPathBase.HasValue && resolvedPath.StartsWith(virtualPathBaseProvider.VirtualPathBase.Value, StringComparison.OrdinalIgnoreCase)) { resolvedPath = resolvedPath.Substring(virtualPathBaseProvider.VirtualPathBase.Value.Length); cacheEntryOptions.AddExpirationToken(fileProvider.Watch(resolvedPath)); fileInfo = fileProvider.GetFileInfo(resolvedPath); } if (fileInfo.Exists) { value = GetHashForFile(fileInfo); cacheEntryOptions.SetSize(value.Length * sizeof(char)); // Cache module static files to the shared cache. if (fileProvider is IModuleStaticFileProvider) { _sharedCache.Set(resolvedPath, value, cacheEntryOptions); } else { _cache.Set(cacheKey, value, cacheEntryOptions); } return(QueryHelpers.AddQueryString(path, VersionKey, value)); } } // If the file is not in the current server, set cache so no further checks are done. cacheEntryOptions.SetSize(0); _cache.Set(cacheKey, String.Empty, cacheEntryOptions); return(path); }
public object Set(object key, object value, MemoryCacheEntryOptions options) { return(value); }
/// <summary> /// Return the result of the <paramref name="query" /> from the cache. If the query is not cached /// yet, the query is materialized and cached before being returned. /// </summary> /// <typeparam name="T">The generic type of the query.</typeparam> /// <param name="query">The query to cache in the QueryCacheManager.</param> /// <param name="options">The cache entry options to use to cache the query.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <param name="tags"> /// A variable-length parameters list containing tags to expire cached /// entries. /// </param> /// <returns>The result of the query.</returns> public static async Task <T> FromCacheAsync <T>(this QueryDeferred <T> query, MemoryCacheEntryOptions options, CancellationToken cancellationToken = default(CancellationToken), params string[] tags) { if (!QueryCacheManager.IsEnabled) { return(await query.ExecuteAsync(cancellationToken).ConfigureAwait(false)); } var key = QueryCacheManager.GetCacheKey(query, tags); object item; if (!QueryCacheManager.Cache.TryGetValue(key, out item)) { item = await query.ExecuteAsync(cancellationToken).ConfigureAwait(false); item = QueryCacheManager.Cache.Set(key, item ?? DBNull.Value, options); QueryCacheManager.AddCacheTag(key, tags); QueryCacheManager.AddCacheTag(key, typeof(T).Name + QueryCacheManager.CacheTypeSuffix); } item = item.IfDbNullThenNull(); return((T)item); }
private MemoryCacheEntryOptions GetMemoryCacheEntryOptions(string relativePath) { var options = new MemoryCacheEntryOptions(); options.AddExpirationTrigger(_fileProvider.Watch(relativePath)); var viewImportsPaths = ViewHierarchyUtility.GetViewImportsLocations(relativePath); foreach (var location in viewImportsPaths) { options.AddExpirationTrigger(_fileProvider.Watch(location)); } return options; }
public static Func <T1, T2, TResult> Create <T1, T2, TResult>(Func <T1, T2, TResult> func, IMemoryCache cache, MemoryCacheEntryOptions options) { return((T1 t1, T2 t2) => { var key = (t1, t2); if (!cache.TryGetValue <TResult>(key, out var result)) { var entry = cache.CreateEntry(key); result = func(t1, t2); entry.SetOptions(options); entry.SetValue(result); // need to manually call dispose instead of having a using // in case the factory passed in throws, in which case we // do not want to add the entry to the cache entry.Dispose(); } return result; }); }
private static IMemoryCache MakeCache(object result = null) { var cache = new Mock<IMemoryCache>(); cache.CallBase = true; cache.Setup(c => c.TryGetValue(It.IsAny<string>(), out result)) .Returns(result != null); var cacheEntryOptions = new MemoryCacheEntryOptions(); cacheEntryOptions.AddExpirationToken(Mock.Of<IChangeToken>()); cache .Setup( c => c.Set( /*key*/ It.IsAny<string>(), /*value*/ It.IsAny<object>(), /*options*/ cacheEntryOptions)) .Returns(result); return cache.Object; }
// Internal for unit testing internal MemoryCacheEntryOptions GetMemoryCacheEntryOptions(IEntryLink entryLink) { var options = new MemoryCacheEntryOptions(); if (ExpiresOn != null) { options.SetAbsoluteExpiration(ExpiresOn.Value); } if (ExpiresAfter != null) { options.SetAbsoluteExpiration(ExpiresAfter.Value); } if (ExpiresSliding != null) { options.SetSlidingExpiration(ExpiresSliding.Value); } if (Priority != null) { options.SetPriority(Priority.Value); } options.AddEntryLink(entryLink); return options; }
public object Set(object key, object value, MemoryCacheEntryOptions cacheEntryOptions) { throw new NotImplementedException(); }
public Task RenewAsync(string key, AuthenticationTicket ticket) { var options = new MemoryCacheEntryOptions(); var expiresUtc = ticket.Properties.ExpiresUtc; if (expiresUtc.HasValue) { options.SetAbsoluteExpiration(expiresUtc.Value); } options.SetSlidingExpiration(TimeSpan.FromHours(1)); // TODO: configurable. _cache.Set(key, ticket, options); return Task.FromResult(0); }