Removing specific items from Cache (ASP.NET)

前端 未结 5 788
执念已碎
执念已碎 2021-02-14 02:07

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 d

相关标签:
5条回答
  • 2021-02-14 02:19

    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 讨论(0)
  • 2021-02-14 02:22

    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.

    0 讨论(0)
  • 2021-02-14 02:23

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

    0 讨论(0)
  • 2021-02-14 02:26

    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.

    0 讨论(0)
  • 2021-02-14 02:34

    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.

    0 讨论(0)
提交回复
热议问题