Search code examples
c#.netcachingmemorycache

.NET Caching - cache expires very early


I'm trying to use MemoryCache in .Net 4.5 to store an object for 1 month (absolute expiration - 1 month from when the cache is created).

Problem - The cache seems to expire within a day - sometimes within a few hours, in fact.

Code Snippet

// Setting the cache with absolute expiration time of 1 month:
string objName = "myObj";
MemoryCache memCache = MemoryCache.Default;
memCache.Add(tokenID, myObj, DateTimeOffset.UtcNow.AddMonths(1));

// Accessing the cache later
MemoryCache getCache = MemoryCache.Default;
getCache.Get(tokenID);

Questions

  1. Am I setting the cache correctly? I haven't seen any examples that use AddMonths(), but there are many that use AddDays() - should that matter though?
  2. Is there a max amount of time that I could use for absolute expiration? (I haven't come across any examples that set caches for more than 30 days, while not using infinite expiration time.)
  3. What else could be causing the cache to expire so quickly?

Thank you so much!


Solution

  • Check the IIS AppPool setting you are using for your web application. Under Advanced Settings, there is a setting for Idle Time-out (minutes). If your site is idle for longer that this period, the worker process is shut down.