gpt4 book ai didi

c# - 如何从 ASP.NET Core 中的 IMemoryCache 中删除(重置)所有对象

转载 作者:IT王子 更新时间:2023-10-29 04:54:22 27 4
gpt4 key购买 nike

Remove 方法可以通过键从 IMemoryCache 中删除对象。有没有办法重置整个缓存并删除所有对象?

使用 How to clear MemoryCache? 所述的 Dispose 方法不起作用:

ObjectDisposedException: Cannot access a disposed object.
Object name: 'Microsoft.Extensions.Caching.Memory.MemoryCache'.

最佳答案

参见 Cache in-memory in ASP.NET Core ,特别是关于 Cache dependencies .

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();
}
}

关于c# - 如何从 ASP.NET Core 中的 IMemoryCache 中删除(重置)所有对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34406737/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com