Created
February 14, 2020 06:57
-
-
Save KarateJB/4ca1e090a3481fdf95fdaea2d3506a4a to your computer and use it in GitHub Desktop.
[.NET Core] Get all entries from MemoryCache
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// <summary> | |
/// Get all CacheEnries in MemoryCache | |
/// </summary> | |
/// <param name="cache">IMemoryCache</param> | |
/// <returns>List of CacheEntry</returns> | |
public static IList<ICacheEntry> GetAllCacheEntries(this IMemoryCache cache) | |
{ | |
// CacheEtries | |
var cacheEntries = new List<ICacheEntry>(); | |
var field = typeof(MemoryCache).GetProperty("EntriesCollection", BindingFlags.NonPublic | BindingFlags.Instance); | |
var cacheEntriesCollection = field.GetValue(cache) as dynamic; | |
if (cacheEntriesCollection != null) | |
{ | |
foreach (var cacheItem in cacheEntriesCollection) | |
{ | |
// Get the "Value" from the key/value pair which contains the cache entry | |
ICacheEntry cacheItemValue = cacheItem.GetType().GetProperty("Value").GetValue(cacheItem, null); | |
// Add the cache entry to the list | |
cacheEntries.Add(cacheItemValue); | |
} | |
} | |
return cacheEntries; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment