简体   繁体   中英

Get all cache in ASP.NET Core 1

The version is rc1. In my old project there are codes like

System.Web.Caching.Cache c = System.Web.HttpRuntime.Cache;
System.Collections.IDictionaryEnumerator cacheEnumerator = c.GetEnumerator();
while (cacheEnumerator.MoveNext())
{....}

In core 1 I use IMemoryCache and I can get cache by key like

var c = this._memoryCache;
var data = c.Get("data");

I want to make a view to list all cache. How can I get all cache in Core 1?

Looking at the source of ASP.NET Core's MemoryCache implementation on github , you can see that the class doesn't expose any functionality to scan or iterate the list of cache entries.

The closest you can do is use reflection to read the inner cache dictionary:

 private readonly Dictionary<object, CacheEntry> _entries;

Wrap the reflection code in an extension method that accepts an IMemoryCache and returns an IEnumerable<CacheEntry> and you're good - but there are several risks involved:

  1. This implementation is specific to the current, pre-release version of ASP.NET CORE. This could change in newer versions, since it's an internal implementation detail and not part of the contract.
  2. This is specific to the implementation of Microsoft.Extensions.Caching.Memory.MemoryCache, which is just one implementation of IMemoryCache . You might replace it with a different implementation one day, which will break.
  3. The implementation contains a set of locks to manage concurrent access to the cache entries. If you iterate over the inner dictionary directly, you can run into concurrency errors when you try to read an entry while it's being updated. The first step is to never update the cache entry directly, and always go through IMemoryCache 's methods, but even then, there's a risk.

Knowing the risks, though, you can go forth and get your job done.

Instead of using reflection you could also add to a Dictionary every time you add to the cache and maintain it with callbacks from cache policies. Less dependent on the .net MemoryCache if you handle it this way. Would probably have some concurrency issues with the Dictionary, but as long as it is locked on updates and deletes it should do fine.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM