代码之家  ›  专栏  ›  技术社区  ›  Greg

在ASP.NET缓存对象中循环键

  •  7
  • Greg  · 技术社区  · 14 年前

    在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"];
    

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

    但是我想实现一个cache clear函数,它可以清除缓存值 我不知道的地方 整体 密钥名称。似乎有一种联想 数组在这里,它应该是可能的(?)

    有谁能帮我找出一种循环存储的缓存键和 对它们执行简单的逻辑?以下是我想要的:

    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);
            }
        }
    }
    
    1 回复  |  直到 13 年前
        1
  •  5
  •   drzaus tranceporter    11 年前

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

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

    int i = 0;
    while (i < Cache.Keys.Length){
       if (Cache.Keys(i).Contains(keyName){
          Cache.Remove(Cache.Keys(i))
       } 
       else{
          i ++;
       }
    }
    
        2
  •  0
  •   Yanga    5 年前

    在.net core中执行此操作的另一种方法:

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