Can I iterate over the .NET4 MemoryCache?

后端 未结 3 689
梦毁少年i
梦毁少年i 2021-02-18 21:01

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 rel

相关标签:
3条回答
  • 2021-02-18 21:55

    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.

    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.

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

    0 讨论(0)
  • 2021-02-18 22:05

    Consider using ChangeMonitors, which allow you to automatically evict stale entries when certain conditions are met.

    See Is there some sort of CacheDependency in System.Runtime.Caching?

    This is similar to System.Web.Caching CacheDependencys, who allow you to evict entries when files or other cache entries change.

    0 讨论(0)
  • 2021-02-18 22:08

    In 2014,

    This is the correct way to get all the items:

    Dim AllItems = MemoryCache.Default.Select(Of ItemType)(Function(O) O.Value)

    Hope this helps someone.

    0 讨论(0)
提交回复
热议问题