Can I iterate over memory .NET4 MemoryCache?

I am using the cache provided by System.Runtime.Caching.MemoryCache .

I would like to list the elements of the cache so that I can nullify (extrude and then reload) the elements as such

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

But official docs are found here state:

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

Should there really be a simple and effective way to iterate over cache elements?

+19
c # caching
Nov 05 '11 at 9:50 a.m.
source share
3 answers

The suggestions made so far have been wonderful, but my need is still stated: for iterating over cache elements . It seems to be such a simple task, and I expect that inside the cache inside there is some sort of list structure. Requires documents and feature set for MemoryCache .

So, as discussed above, I added a list to the cache adapter class, which contains a link to every item that I put in the cache. If I need to iterate over the cache - not only for invalidity, but also for collecting statistics, etc. - then I iterate over my list.

If the number of items put in the cache does not change, this is a reasonable decision. If the number changes, you need to insert / delete through the adapter class to keep the list in sync with the actual cache. It is useless, but it works, and avoids the primary sanctions mentioned in the documents.

I hope that the caching provider MemoryCache will be hidden in the next release of the platform.

+9
Nov 06 '11 at 10:51
source share

Consider using ChangeMonitors, which can automatically delete obsolete entries under certain conditions.

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

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

+1
Nov 05 2018-11-11T00:
source share

In 2014

This is the correct way to get all the elements:

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

Hope this helps someone.

-2
Nov 21 '14 at 8:33
source share



All Articles