How to prevent ASP.NET from removing items from ca

2019-03-19 04:27发布

I want to permanently add an item to the cache. I am using the following syntax:

HttpContext.Current.Cache.Insert(cacheName, c, null, Cache.NoAbsoluteExpiration, Cache.NoSlidingExpiration);

I have found out, that ASP.NET still sometimes removes items from the cache.

Any ideas on how to prevent this (in addition to dropping the cache and using Dictionary stored in a static member?

Matra

7条回答
冷血范
2楼-- · 2019-03-19 04:57

You cannot ever completely prevent something from being removed from the ASP.NET Cache (i.e. the HttpContext.Current.Cache object) and this is very much by design.

Please see the section in the MSDN Article ASP.NET Caching Overview called "Automatic Data Removal", which gives the most pertinent information regarding items being removed from the cache.

It states:

ASP.NET can remove data from the cache for one of these reasons:

  • Because memory on the server is low, a process known as scavenging.
  • Because the item in the cache has expired.
  • Because the item's dependency changes.

To help you manage cached items, ASP.NET can notify your application when items are removed from the cache.

Scavenging is the process of deleting items from the cache when memory is scarce. Items are removed when they have not been accessed in some time or when items are marked as low priority when added to the cache. ASP.NET uses the CacheItemPriority object to determine which items to scavenge first. For more information see How to: Add Items to the Cache.

It's for this reason (Scavenging, if no other) that you can never absolutely rely upon an item that you may have previously placed in the Cache and explicitly marked it with NoSlidingExpiration and NoAbsoluteExpiration, and possibly even marked it as a high priority item, as still being there in the Cache at a later point in time.

查看更多
登录 后发表回答