Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HttpContext.Current.Cache - When does this gets cleared automatically?

Tags:

.net

caching

iis

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 ?

like image 532
Riz Avatar asked Aug 23 '11 10:08

Riz


People also ask

What is the time after an item cached in the HttpContext session is it removed from the cache?

User level cache Data cached at the session scope will be lost. Based on the web. config file configuration, the default is 20 minutes; when there is no user activity on the application, or when the user uses ASP.NET session functionality. HttpContext.

What is the time after an item cached in HttpContext session?

Setting the Application IdleTimeout property within IIS You can set the IdleTimeout property within your Application Pool settings in IIS to avoid your actual application timing out. The default value is 20 minutes.

Is HttpContext current Cache thread safe?

HttpContext isn't thread-safe. Reading or writing properties of the HttpContext outside of processing a request can result in a NullReferenceException.


2 Answers

The cache is held in memory until the process is stopped.

So, resetting IIS or recycling the application pool would also clear the cache.

like image 185
Oded Avatar answered Nov 15 '22 22:11

Oded


According to MSDN, the cache will be cleared on the following scenarios:

  1. The code manually clears an entry.
    • By using the Remove method of the Cache object.
  2. The cache entry expires.
    • By using the absoluteExpiration or slidingExpiration parameters of the Add and Insert methods of the Cache object.
  3. A dependency of the cached item is removed from the cache.
    • By defining a dependency through the use of the CacheDependency class when adding items to the cache.
    • Removing a dependency will remove/expire all dependent items.
  4. The host process ends (application or IIS reset, application pool recycle, etc).
  5. System memory becomes scarce (automatic - called scavenging - see below).

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.

The Cache class offers powerful features that allow you to customize how items are cached and how long they are cached. For example, when system memory becomes scarce, the cache automatically removes seldom-used or low-priority items to free memory. This technique is referred to as scavenging, and is one of the ways that the cache ensures that out-of-date data does not consume valuable server resources.

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.

var expiresAt = DateTime.UtcNow.Date.AddHours(24);
System.Web.HttpContext.Current.Cache.Insert(
    "myKey",
    myValue,
    null,
    expiresAt,
    Cache.NoSlidingExpiration,
    CacheItemPriority.High,
    null
);

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 the Cache 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 or Insert methods of the Cache 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:

  • Caching Application Data
  • How to: Notify an Application When an Item Is Removed from the Cache

API:

  • Cache.Remove Method
  • Cache.Add Method
  • Cache.Insert Method
  • CacheDependency Class
  • CacheItemPriority Enumeration
  • Cache.EffectivePercentagePhysicalMemoryLimit Property

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.

like image 40
Rodrigo Lima Avatar answered Nov 15 '22 21:11

Rodrigo Lima