我可以遍历.NET4的MemoryCache?遍历、MemoryCache

2023-09-07 14:16:42 作者:破茧。幻化成蝶

我使用的是由 System.Runtime.Caching.MemoryCache 提供的高速缓存。

I'm using the cache provided by System.Runtime.Caching.MemoryCache.

我想枚举缓存的项目,这样我可以无效(驱逐然后重新加载)的项目为如

I'd like to enumerate over the cache's items so that I can invalidate (evict then reload) items as such

foreach (var item in MemoryCache.Default) { item.invalidate() }

但官方文档found这里状态:

重要提示:检索一个枚举的的MemoryCache实例是   资源密集型和阻断的操作。因此,普查员应   不能在实际应用中使用。

!Important: Retrieving an enumerator for a MemoryCache instance is a resource-intensive and blocking operation. Therefore, the enumerator should not be used in production applications.

当然,必须有一个简单而有效的方式来遍历缓存中的项目?

Surely there must be a simple and efficient way to iterate over the cache's items?

推荐答案

发至今已经很大,但我需要的是仍表示建议:遍历缓存的项目。这似乎是这样一个简单的任务,我想到的是,高速缓存内部有某种形式的表结构的反正。该文档和要素集的MemoryCache 的缺憾。

Suggestions made so far have been great, but my need is still as stated: to iterate over the cache's items. It seems like such a simple task, and I expect that the cache internally has some sort of list structure anyway. The docs and the feature set for MemoryCache are wanting.

所以如上所述,我添加了一个列表,我的缓存适配器类,其中包含引用的每个项目我在缓存中占有一席之地。如果我需要遍历缓存 - 不只是为无效,但对收集统计数据,等等 - 然后我遍历我的列表

So as discussed above, I've added a list to my cache adapter class, which holds a reference to each item I place in the cache. If I need to iterate over the cache--not just for invalidation, but for gathering statistics, etc.--then I iterate over my list.

如果放置在缓存中的项目数不发生变化,那么这是一个合理的解决方案。如果号码不改变,那么你需要插入/通过适配器类中删除,从而使列表同步与实际的缓存。凌乱的,但它的工作原理,并避免在文档提到的PERF的处罚。

If the number of items placed in the cache does not change, then this is a reasonable solution. If the number does change, then you need to insert/remove via the adapter class, so as to keep the list in sync with the actual cache. Messy but it works, and avoids the perf penalties alluded to in the docs.

希望的MemoryCache 缓存提供者将被充实,在下一版本的平台。

Hopefully MemoryCache cache provider will be fleshed-out in the next platform release.