我可以找到一个remove方法,通过它的键从IMemoryCache中删除对象.有没有办法重置整个缓存并删除所有对象?
I can find a remove method to remove an object from IMemoryCache by its key. Is there a way to reset the whole cache and remove all objects?
如何清除MemoryCache? 链接中提供的Dispose方法在asp 5中给了我一个例外.ObjectDisposedException: Cannot access a disposed object. Object name: 'Microsoft.Extensions.Caching.Memory.MemoryCache'.
How to clear MemoryCache? Dispose method provided in the link gives me an exception in asp 5. ObjectDisposedException: Cannot access a disposed object. Object name: 'Microsoft.Extensions.Caching.Memory.MemoryCache'.
推荐答案请参见 ASP.NET Core中的内存缓存,特别是关于 缓存依赖项.
See Cache in-memory in ASP.NET Core, specifically the section on Cache dependencies.
使用CancellationTokenSource可以将多个缓存条目作为一个组逐出
Using a CancellationTokenSource allows multiple cache entries to be evicted as a group
此代码对我有用:
public class CacheProvider { private static CancellationTokenSource _resetCacheToken = new CancellationTokenSource(); private readonly IMemoryCache _innerCache; /* other methods and constructor removed for brevity */ public T Set<T>(object key, T value) { /* some other code removed for brevity */ var options = new MemoryCacheEntryOptions().SetPriority(CacheItemPriority.Normal).SetAbsoluteExpiration(typeExpiration); options.AddExpirationToken(new CancellationChangeToken(_resetCacheToken.Token)); _innerCache.Set(CreateKey(type, key), value, options); return value; } public void Reset() { if (_resetCacheToken != null && !_resetCacheToken.IsCancellationRequested && _resetCacheToken.Token.CanBeCanceled) { _resetCacheToken.Cancel(); _resetCacheToken.Dispose(); } _resetCacheToken = new CancellationTokenSource(); } }更多推荐
如何从ASP.NET Core中的IMemoryCache删除所有对象(重置)
发布评论