2010-11-29 119 views
7

缓存在ASP.NET看起来像它使用某种关联数组:通过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); 
     } 
    } 
} 
+0

缓存是你的控制之下 - 你为什么不知道的东西,都在那里的名字? – 2010-11-29 10:49:06

回答

5

从任何集合类型 - foreach循环依赖于使用枚举它不会让你从集合中删除项目删除项目时,不要使用foreach循环(如果迭代的集合中添加或删除了项目,枚举器将抛出异常。

使用简单而遍历缓存键,而不是:

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

这是线程安全的吗?如果另一个线程在运行此代码时正在修改缓存(例如,从缓存中添加和/或从缓存中删除内容),该怎么办? – 2015-05-05 20:04:10