In my Web forms application I am using HttpContext.Current.Cache to store some information which different forms use to avoid going to db every time.
My Question is, when will this get cleared? Or it will remain there until I remove it through code or restart IIS ?
According to MSDN, the cache will be cleared on the following scenarios:
Remove
method of theCache
object.absoluteExpiration
orslidingExpiration
parameters of theAdd
andInsert
methods of theCache
object.CacheDependency
class when adding items to the cache.Scavenging
Even though cases 1 to 4 are mostly self-explanatory, the system memory availability scenario might not be evident at first. See the quote below from the MSDN article on caching application data.
According to the same article, you can set priority levels on your cached items to try to secure your most important items from being automatically removed by using the
CacheItemPriority
enumeration.Note that you also have the option of setting the priority to
NotRemovable
, which would disable the automatic removal of this item through scavenging. However, please note that this is not the default behavior.Also note that, if you use large amounts of memory through cache by setting the priority to
NotRemovable
, your application might throw run time memory availability errors.Information on how much of your system's memory is available for your application's cache can be retrieved through the property
EffectivePercentagePhysicalMemoryLimit
of theCache
object.Logging/Debugging
If you wish to carefully understand the status of the cache on your application through logs (for instance), it's usually useful to look at the moments where the item is inserted and removed from the cache.
Logging the moment where the item is inserted is usually pretty simple, since you only have to look for calls to the
Add
orInsert
methods of theCache
object.However, since cached items may be automatically removed, to log the removal of an item, you should use the
CacheItemRemovedCallback
delegate type when inserting items to the cache.This can be really useful when debugging/improving legacy applications that rely heavily on caching data.
See MSDN article below for more details.
Sources:
MSDN Articles:
API:
I know this question is back from 2011. However, it took me some time to figure out a bug in a legacy application I was working on that was caused by the automatic clear up policy based on available physical memory.
Hopefully, this answer will help someone else.
And thanks to @J. Ed and @Oded for their answer and comments. They helped me get in the right track to find the issue.
The cache is held in memory until the process is stopped.
So, resetting IIS or recycling the application pool would also clear the cache.