Removing specific items from Cache (ASP.NET)

2020-06-12 03:08发布

问题:

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?

回答1:

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.



回答2:

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



回答3:

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.



回答4:

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.



回答5:

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.