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?
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.
You could write a subclass of CacheDependency
that does the invalidation appropriately.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With