Removing specific items from Cache (ASP.NET)

前端 未结 5 807
执念已碎
执念已碎 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:22

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

    List itemsToRemove = new List();
    
    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.

提交回复
热议问题