Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing specific items from Cache (ASP.NET)

I am adding a bunch of items to the ASP.NET cache with a specific prefix. I'd like to be able to iterate over the cache and remove those items.

The way I've tried to do it is like so:

    foreach (DictionaryEntry CachedItem in Cache)
    {
        string CacheKey = CachedItem.Key.ToString();
        if(CacheKey.StartsWith(CACHE_PREFIX){
            Cache.Remove(CacheKey);
        }
    }

Could I be doing this more efficiently?

I had considered creating a temp file and adding the items with a dependancy on the file, then just deleting the file. Is that over kill?

like image 940
Adrian Hope-Bailie Avatar asked Apr 01 '09 09:04

Adrian Hope-Bailie


2 Answers

You can't remove items from a collection whilst you are iterating over it so you need to do something like this:

List<string> itemsToRemove = new List<string>();

IDictionaryEnumerator enumerator = Cache.GetEnumerator();
while (enumerator.MoveNext())
{
    if (enumerator.Key.ToString().ToLower().StartsWith(prefix))
    {
        itemsToRemove.Add(enumerator.Key.ToString());
    }
}

foreach (string itemToRemove in itemsToRemove)
{
    Cache.Remove(itemToRemove);
}

This approach is fine and is quicker and easier than cache dependencies.

like image 109
Rob West Avatar answered Oct 02 '22 20:10

Rob West


You could write a subclass of CacheDependency that does the invalidation appropriately.

like image 41
mmx Avatar answered Oct 02 '22 18:10

mmx