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

编程入门 行业动态 更新时间:2024-10-26 21:24:15
本文介绍了如何从ASP.NET Core中的IMemoryCache删除所有对象(重置)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我可以找到一个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删除所有对象(重置)

本文发布于:2023-11-13 21:41:16,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1585393.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:对象   NET   ASP   IMemoryCache   Core

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!