asp.net - 循环访问 ASP.NET 缓存对象中的键

标签 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, null checks can be performed to see if cache exists yet:
if(Cache["TestCache"] == null) {
    Cache.Insert(PerformComplicatedFunctionThatNeedsCaching());
}
someValue = Cache["TestCache"];

如您所见,对缓存对象执行 null 检查非常有用。

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

任何人都可以帮我找出一种循环存储的缓存键和 对它们执行简单的逻辑?这就是我所追求的:

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 ++;
   }
}

关于asp.net - 循环访问 ASP.NET 缓存对象中的键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4302700/

相关文章:

xml - 如何在 TimesTen 数据库中缓存 XMLTYPE 表?

javascript - 当使用 Javascript 的 Reflect API 构建一个扩展另一个类的实例时,为什么索引数组是共享作用域?

.net - 可以在 aspx 页面上显示来自代码隐藏的实际源代码(对于代码示例页面)

asp.net - 当 sql server 离线时禁用(礼貌地)一个网站

php - 管理 key (在 memcache 中)以防止缓存值过时的最佳方法是什么?

ruby-on-rails-3 - 如何在Ruby on Rails 3中缓存查询

string - 为什么不能将字符串键存储在关联数组中?

actionscript-3 - ActionScript - 比较和删除复杂数组的重复项?

javascript - Supersized.js 背景未在母版页中呈现

c# - 使 aspx 身份验证 cookie 无效