通过ASP.NET缓存对象中的键循环

通过ASP.NET缓存对象中的键循环,asp.net,caching,associative-array,Asp.net,Caching,Associative Array,ASP.NET中的缓存似乎使用了某种关联数组: // Insert some data into the cache: Cache.Insert("TestCache", someValue); // Retrieve the data like normal: someValue = Cache.Get("TestCache"); // But, can be done associatively ... someValue = Cache["TestCache"]; // Also, n

ASP.NET中的缓存似乎使用了某种关联数组:

// Insert some data into the cache:
Cache.Insert("TestCache", someValue);
// Retrieve the data like normal:
someValue = Cache.Get("TestCache");

// But, can be done associatively ...
someValue = Cache["TestCache"];

// Also, null checks can be performed to see if cache exists yet:
if(Cache["TestCache"] == null) {
    Cache.Insert(PerformComplicatedFunctionThatNeedsCaching());
}
someValue = Cache["TestCache"];
如您所见,对缓存对象执行空检查非常有用

但是我想实现一个可以清除缓存值的缓存清除函数 我不知道整个键名。因为似乎有一种联想 数组,它应该是可能的(?)

有人能帮我找到一种循环存储的缓存密钥和密码的方法吗 对它们执行简单的逻辑?以下是我想要的:

static void DeleteMatchingCacheKey(string keyName) {
    // This foreach implementation doesn't work by the way ...
    foreach(Cache as c) {
        if(c.Key.Contains(keyName)) {
            Cache.Remove(c);
        }
    }
}

从任何集合类型中删除项时不要使用foreach循环-foreach循环依赖于使用枚举器,该枚举器不允许您从集合中删除项(如果枚举器迭代的集合中添加或删除了项,则枚举器将引发异常)

使用简单的while循环缓存键:

int i = 0;
while (i < Cache.Keys.Length){
   if (Cache.Keys(i).Contains(keyName){
      Cache.Remove(Cache.Keys(i))
   } 
   else{
      i ++;
   }
}
inti=0;
while(i
在.net core中执行此操作的另一种方法:

var keys = _cache.Get<List<string>>(keyName);
foreach (var key in keys)
{
   _cache.Remove(key);
}
var keys=\u cache.Get(keyName);
foreach(var键入键)
{
_缓存。删除(键);
}

缓存在您的控制之下-为什么您不知道其中的东西的名称?此线程安全吗?如果另一个线程正在修改缓存(例如,添加和/或从缓存中删除东西),该怎么办此代码正在运行时?缓存类是线程安全的,因此此代码不会引发异常。但是,如果在上次检查Cache.Keys.Length之后调用Cache.Add(),则可能不会从缓存中删除所有项。