Sunday, May 29, 2011

ASP.Net Cache and updating the value using the Indexer

What happens if you update an object already in the cache using the indexer, something like -

HttpRuntime.Cache[“someKey”] = value; ?

A. The cached object is overwritten with the new value while retaining the other information like expiration (be it absolute or sliding) and cache dependencies.

B. The cache object is overwritten and the other cache information are reset to defaults.

The correct answer is B, calling the indexer on the cache object internally calls Cache.Insert(object) which passes default values for the CacheDependency, and uses default expiration policy (i.e. the object never expires unless the server is low on memory). So the next time,  you find that your objects in cache are not honoring the cache TTLs or not getting evicted on dependency changes, make sure that you are not updating the object somewhere in the code using the indexer. I learnt it the hard-way while debugging the issue with a “forever-cached” object on our production site!

No comments:

Post a Comment