2010-11-29 232 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