Just clear all items from cache

Oct 31, 2014 at 4:12 PM
I was trying to clear cache with method Purge, but it doesn't clear it. I'd like to remove all cache items not depending on cache policies. What should I do?

Nov 12, 2014 at 5:20 AM
I am assuming you are talking about the InMemoryCache (because the ICache interface does not define the Purge method). The way the InMemoryCache works is that it removes outdated entries lazily. I.e. if an item is expired it won't be removed immediately but only the next time asks for it. It creates a situation where, if you have many queries that are sent only once, the cache can grow and contain multiple expired entries that are taking space but are basically useless. In this scenario you call Purge to remove these entries. Currently there is no mechanism to clean the cache completely. You can emulate by invoking the InvalidateSets method and pass all the entity sets which will remove all the items from the cache. It won't be as fast as just clearing the _cache Dictionary but should work.

Out of curiosity why do you need to remove all the entries from the cache?

Nov 12, 2014 at 7:08 AM
Thanks Pawel for your answer!

Yes, I thought about InMemoryCache. In case I change anything in database manually I would like to have a button in administrative module to clear the cache, because of data in db are changed. And as I understood InMemoryCache won't get it.
I was trying to work with InvalidateSets, but there is a parameter IEnumerable<string> which means that I should pass all entities to invalidate what in code I don't know. Also InvalidateItem takes parameter an entity. All items in cache were inserted automatically, how can I find entities I need to invalidate?

Maybe I didn't understand something, can you help me please, does InMemoryCache have some other possibilities to clear it?

Many thanks,
Nov 14, 2014 at 7:12 AM
Hi Andrej,

The InvalidateSets method does not take entities but entity set names. You can get all the EntitySet names in your model using the following Linq query:
((IObjectContextAdapter)ctx).ObjectContext.MetadataWorkspace.GetEntityContainer("CodeFirstDatabase",DataSpace.SSpace).EntitySets.Select(e => e.Name))
Use this as the argument of InvalideSets and then optionally Purge the cache (to free memory) and you should be good to go.