how long, by default does stuff stay in httpcache if i don't put an explicit expiration?

896 Views Asked by At

i have the following code to cache some expensive code.

  private MyViewModel GetVM(Params myParams)
    {
        string cacheKey = myParams.runDate.ToString();
        var cacheResults = HttpContext.Cache[cacheKey] as MyViewModel ;
        if (cacheResults == null)
        {
            cacheResults = RunExpensiveCodeToGenerateVM(myParams);
            HttpContext.Cache[cacheKey] = cacheResults;
        }                
   return cacheResults;
   }

will this stay in the cache forever? until the server reboots or runs out of memory?

1

There are 1 best solutions below

0
On BEST ANSWER

will this stay in the cache forever?

This will depend on the particular cache provider you are using. For example if you are using the default in-memory cache it might expire if the server starts running low on memory or if the application pool is recycled. But if you are using some other cache provider, like for example a distributed cache like memcached or AppFactory this will depend on the particular implementation.

The rule of thumb is to never assume that something is inside the cache because you previously stored it. Always check for the presence of the item in the cache first and if not present fetch it and store in the cache again.