HttpContext.Current.Cache item null after page refresh

前端 未结 2 533
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-05 17:52

I\'ve a C# web page in which I\'m storing a List<> object in the server cache, using HttpContext.Current.Cache. The object is saved in the cache after the first page load

2条回答
  •  心在旅途
    2021-01-05 18:33

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

    Pass CacheItemPriority.NotRemovable to Cache.Insert() to prevent that from happening. Lookup CachéItemPriority on MSDN.

    An IIS application pool restart by long idle time, web.config/binary change, etc. will also wipe your cache. Check this other SO post, HttpRuntime.Cache.Insert() Not holding cached value

    About creating a job to refresh the cache; I don't think there is a rule of thumb for the best Cache strategy. It will heavily depend on how your users interact with your web page, how often, how concurrent, and specially, how much time does it take to generate that data when the cache is not hit.

    If the time it takes to generate the data is unacceptable for any user, you can set up a job that refreshes the cache, but it's interval should be less than the sum of the cache TTL + time that the generation/retrieval takes. For example, if your cache is 30m and it takes 2m to generate the data, your refresh interval must be 28m or less, to avoid any user to hit an empty cache.

提交回复
热议问题