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
If you want something stored in memory permanently (i.e. for the life of the AppDomain) then a static field (in your case, a
Dictionary<TKey,TValue>
) is your best bet.Once the CLR has loaded the containing type into memory your
Dictionary
will be held in memory until the AppDomain unloads.Use Cache.Add() and set the cache priority extremely high(CacheItemPriority.NotRemovable), this will help it stay in the cache.
System.Web.Caching.CacheItemPriority.NotRemovable
This still seems to not guarantee it being in the cache, but it also sets it so high its highly unlikely that it will be... but you will still need to check if its there and re-cache if not... (looks like some people on the intertubes don't like using this high a cache setting... and some do... depends on your exact scenario i guess...)
good luck
Wrong! You CAN prevent your items from being removed from the asp.net cache if you mark the item with CacheItemPriority.NotRemovable. Each and every other cached data (application, session, etc...) are stored in the HttpRuntime cache this way.
People always tend to believe that even this priority doesn't prevent your data to expire, but this is due to the lack of proper documentation. I think the confussion comes with the ability to manually remove such an item from the cache OR the item being removed due to dependencies setted for it.
So, if you never manually remove it, and never specify dependencies that can get it removed, you have your item in there for the life of the appdomain.
My answer is not correct. Please see here for a correct answer.
You can't prevent ASP.NET from removing items from the cache (e.g. when memory gets low).
If you need to store data for the whole lifetime of the application, then put it into the ApplicationState collection, e.g:
This is similar to the SessionState collection, but as the name says, it's application-wide.
You should be prepared to handle a cache miss and reload the information in your cache as required. See here
Try to combine the CacheItemPriority.NotRemovable option with:
This should override the machine.config setting.