/// <summary>
/// 获取所有缓存键
/// </summary>
/// <returns></returns>
public static List<string> GetCacheKeys()
{
//第一种:.NET7.0以前的写法
//const BindingFlags flags = BindingFlags.Instance | BindingFlags.NonPublic;
//var entries = Cache.GetType().GetField("_entries", flags).GetValue(Cache);
//var cacheItems = entries as IDictionary;
//var keys = new List<string>();
//if (cacheItems == null) return keys;
//foreach (DictionaryEntry cacheItem in cacheItems)
//{
// keys.Add(cacheItem.Key.ToString());
//}
//return keys;
//第二种:.NET7.0以后的写法
const BindingFlags flags = BindingFlags.Instance | BindingFlags.NonPublic;
var coherentStateFiledInfo = Cache.GetType().GetField("_coherentState", flags);
var coherentStateValue = coherentStateFiledInfo.GetValue(Cache);
var entriesFiledInfo = coherentStateFiledInfo.FieldType.GetRuntimeFields().Where(f => f.Name == "_entries").FirstOrDefault();
var entries = entriesFiledInfo.GetValue(coherentStateValue);
var cacheItems = entries as IDictionary;
var keys = new List<string>();
if (cacheItems == null) return keys;
foreach (DictionaryEntry cacheItem in cacheItems)
{
keys.Add(cacheItem.Key.ToString());
}
return keys;
}
MemoryCache获取所有缓存键在.NET7.0前后的写法
于 2024-05-11 11:30:42 首次发布