HttpContext.Current.Cache item null after page refresh

I have a C # webpage in which I store a List <> object in a server cache using HttpContext.Current.Cache. The object is cached after loading the first page. When I refresh the page, the cache object is NULL. Any thoughts?

In addition, I would like to set up a “job” to recreate the object every 30 minutes. I would like to serve the cached version until a new one is created, and then replace the old one with the new one. How to do it?

In my Global.asax, in Application_Start, I have the following:

HttpRuntime.Cache.Insert("MainADList", Uf.GetUsers(), null, Cache.NoAbsoluteExpiration, TimeSpan.FromMinutes(30)); 

When I need it, I do the following:

  MainADList = (Users)HttpRuntime.Cache["MainADList"]; 

This is for the most part null. Not always, but almost always.

+4
source share
2 answers

Even if you populate your cache with Cache.NoAbsoluteExpiration + Cache.NoSlidingExpiration , ASP.NET can remove items from the cache (that is, when free system memory is low).

Pass CacheItemPriority.NotRemovable to Cache.Insert () to prevent this from happening. Search for CachéItemPriority on MSDN.

Restarting the IIS application pool with long downtime, changing web.config / binary, etc. will also destroy your cache. Check out this other SO entry, HttpRuntime.Cache.Insert () Does not hold the cached value

About creating a task for updating the cache; I do not think that there is a rule for a better cache strategy. This will largely depend on how your users interact with your web page, how often, at the same time, and especially how long it takes to generate this data when the cache doesn’t hit.

If the time required to generate data is unacceptable for any user, you can set up a task that updates the cache, but its interval should be less than the sum of the TTL cache cache + cache, which is required for generation / search, For example, if your cache is 30 m, and 2 m is required for data generation, the refresh interval should be 28 m or less, to prevent any user from getting into the empty cache.

+4
source

Can you use System.Runtime.Caching instead. This way you are not dependent on the HttpRuntime namespace.

I suspect you are getting null because .Net clears it due to a web server reload. It would be better to do something in accordance with

  public List<User> GetUsers() { var cache = System.Runtime.Caching.MemoryCache.Default; if (cache["MainADList"] == null) { // Rebuild cache. Perhaps for Multithreading, you can do object locking var cachePolicy = new System.Runtime.Caching.CacheItemPolicy() { AbsoluteExpiration = DateTime.Now + TimeSpan.FromMinutes(30) }; var users = Uf.GetUsers(); cache.Add(new System.Runtime.Caching.CacheItem("MainADList", users), cachePolicy); return users; } return cache["MainADList"] as List<User>; } 
+2
source

All Articles