【问题标题】:Looping through keys in ASP.NET cache object循环遍历 ASP.NET 缓存对象中的键
【发布时间】:2011-05-17 04:56:18
【问题描述】:

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

【问题讨论】:

  • 缓存在你的控制之下——你为什么不知道里面的东西的名字?

标签: asp.net caching associative-array


【解决方案1】:

从任何集合类型中删除项目时不要使用 foreach 循环 - foreach 循环依赖于使用枚举器,它不允许您从集合中删除项目(如果它正在迭代的集合,枚举器将抛出异常over 已添加或从中删除项目)。

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

int i = 0;
while (i < Cache.Keys.Length){
   if (Cache.Keys(i).Contains(keyName){
      Cache.Remove(Cache.Keys(i))
   } 
   else{
      i ++;
   }
}

【讨论】:

  • 这是线程安全的吗?如果在这段代码运行时另一个线程正在修改缓存(例如从缓存中添加和/或删除内容)怎么办?
  • Cache 类是线程安全的,所以这段代码不会抛出异常。但是,如果在最后一次检查 Cache.Keys.Length 之后调用 Cache.Add(),它可能不会从缓存中删除所有项目。
【解决方案2】:

在 .net core 中的另一种方法:

var keys = _cache.Get<List<string>>(keyName);
foreach (var key in keys)
{
   _cache.Remove(key);
}

【讨论】:

    猜你喜欢
    • 2020-06-09
    • 1970-01-01
    • 1970-01-01
    • 2020-01-28
    • 2019-09-23
    • 2021-11-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多