Is there a way to specify how long data is held in HttpContext.Cache?
You can specify it in the 4th parameter of Cache.Add()
:
public Object Add(
string key,
Object value,
CacheDependency dependencies,
DateTime absoluteExpiration, // After this DateTime, it will be removed from the cache
TimeSpan slidingExpiration,
CacheItemPriority priority,
CacheItemRemovedCallback onRemoveCallback
)
Edit:
If you access the cache via the indexer (i.e. Cache["Key"]
), the method that is called uses no expiration and remains in the cache indefinitely.
Here is the code that is called when you use the indexer:
public void Insert(string key, object value)
{
this._cacheInternal.DoInsert(true, key, value, null, NoAbsoluteExpiration, NoSlidingExpiration, CacheItemPriority.Normal, null, true);
}
Use the Cache.Add method such as:-
HttpContext.Cache.Add("mykey", someObj, null, null, Cache.NoAbsoluteExpiration, new TimeSpan(0, 15, 0), CacheItemPriority.Normal, null);
The above expires in 15 minutes after the last time it was accessed. Alternative you can pass the Cache.NoSlidingExpiration to this parameter and use a specific DateTime in the previous parameter.
Yes there is a way to specify how long data is held in Cache, but none of the previous 2 examples would actually guaranty you'll keep your items in for the expected amount of time passed with either of the 2 time-based parameters of the Add method (absolute or sliding expiration).
The cache is just a cache and its purpose is to speed things up. So you should not expect it to hold onto your data and always be prepared to go fetch it if it's not there.
As you probably know you can have dependencies for the items and they'll expire based on that even if the time has not expired. This is an easy concept but there's another not that easy. The priority.
Based on the priority of your items and coupled with memory pressure, you can find yourself in a situation where you're caching data with good enough expiration times based on your calculations, but you don't get to use that data more than once making your cache just an overhead in such situation.
EDIT: Well I forgot to specify THE actual way to really keep an item in for the amount of time you need to, and that's a product of chosing the desired time-based expiration, no dependency at all, not manually removing it, and using the NotRemovable priority. This is also how inproc session state is internally kept in the httpruntime cache.