问题描述
我可以找到一个 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.net 5 中给了我一个异常. ObjectDisposedException:无法访问已处理的对象.对象名称:Microsoft.Extensions.Caching.Memory.MemoryCache".
How to clear MemoryCache?
Dispose method provided in the link gives me an exception in asp.net 5. ObjectDisposedException: Cannot access a disposed object.
Object name: 'Microsoft.Extensions.Caching.Memory.MemoryCache'.
推荐答案
参见 在 ASP.NET Core 中缓存内存,特别是关于缓存依赖项.
使用 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 核心中的 IMemoryCache 中删除所有对象(重置)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!