开发者

Looping through keys in ASP.NET cache object

Caching in ASP.NET looks like it uses some kind of associative array:

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

As you can see, performing a null check on the cache object is very useful.

But I would like to implement a cache clear function that can clear cache values where I don't know the whole key name. As there seems to be an associative array here, it should be possible (?)

Can anyone help me work out a way of looping through the stored cache keys and per开发者_如何学运维forming simple logic on them? Here's what I'm after:

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


Don't use a foreach loop when removing items from any collection type- the foreach loop relies on using an enumerator which will NOT allow you to remove items from the collection (the enumerator will throw an exception if the collection it is iterating over has items added or removed from it).

Use a simple while to loop over the cache keys instead:

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


An other way to do it in .net core:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜