Removing specific items from Cache (ASP.NET)

2020-06-12 02:50发布

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?

5条回答
倾城 Initia
2楼-- · 2020-06-12 03:08

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.

查看更多
Fickle 薄情
3楼-- · 2020-06-12 03:08

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.

查看更多
Ridiculous、
4楼-- · 2020-06-12 03:12

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

查看更多
淡お忘
5楼-- · 2020-06-12 03:24

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.

查看更多
相关推荐>>
6楼-- · 2020-06-12 03:28

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.

查看更多
登录 后发表回答