ASP.NET has a wonderful built-in framework for managing
Cached items within a website in the namespace System.Web.Caching. It is
accessible from HttpRuntime.Cache (among other ways, such as from System.Web.UI.Page.Cache).
You have great flexibility with the data you may wish to cache. With this
flexibility there is an extremely important piece missing from HttpRuntime.Cache
- and that is thread safety. Not from inside of the Cache, but from the external
code that accesses it. Websites under high load could cause a cache item to be
populated multiple times. Too much thread eats too much cpu!!!
Of the many cache insertion parameters available, for this
article we are going to focus on just two.
absoluteExpiration: When a DateTime
value is passed here in an HttpRuntime.Cache.Insert call, this is the time when
the cache entry will expire from the cache.
onRemoveCallback: When set, this
delegate is executed when an item in the cache is expired, removed, a
dependency was changed, or it was underused.
There are several other items of interest on this method,
but we will focus on these two within the new cache management framework. In
this article, we will explore two areas of interest - a new pattern for locking
string keys and also refreshing data within the HttpRuntime.Cache in background
threads. This can provide for more responsive websites that show data that is
current. We will discuss current patterns, expand on those patterns, and then
discuss the new framework, focusing on key areas. We will save cpu and promote
thread safety!!!