Sunday, April 17, 2011

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?

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

  • It really depends on number of your cache items and how often you do the cleanup. I would worry about it only if it actually was a performance issue - i.e. measure it.

    Your solution is fine to me unless you're doing something extreme.

  • 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.

    Adrian Hope-Bailie : That's what I was afraid of. Thanks
    Vnuk : Nicely done. Although, in next version of .NET I'd like to see Remove method on ALL collections that takes regular expression as input.
  • For the cache clean up , I assume you need to run it manually when you notice there are too many cache items. Using MS lib cache block , it can do this work for you automatically. In the cachingConfiguration; you can set the property maximumElementsInCacheBeforeScavenging; once the number of cache items are over the limit then cache manager will clean out the cache automatically.

  • You should keep another item in cache for this purpose only. Let's say you cache 10.000 items with keys like: cache_prefix_XXX. So adding an item with just cache_prefix as its key and adding the rest of them with a dependency on this key you can control the removal of all of them. One thing to consider would be the priorities. Set that particular item a higher priority than the actual data items.

0 comments:

Post a Comment

Note: Only a member of this blog may post a comment.