Caching frequently accessed or expensive data in memory
boosts application performance by reducing the number of database calls to
retrieve the data. ASP.NET provides two basic caching techniques: page (Page
Output and Page Fragment) and programmatic caching. In my previous article, I
covered the basics of Page Output
. This article’s focus is on caching data via your favorite .NET
language and the Caching API, which allows you to add and remove items from the
cache as necessary.

Caching API

The Caching API is available via the System.Web.Caching
namespace. It contains the Cache object, which contains methods for
manipulating items in the cache. The following methods are available:

  • Add: allows
    you to add a specific item to the cache.
  • Get: retrieves a specific item
    from the cache using a key value.
  • Insert: adds a specific item to
    the cache.
  • Remove: removes a specific item
    from the cache designated by key value.

Weekly .NET tips in your inbox

TechRepublic’s free .NET newsletter, delivered each Wednesday, contains useful tips and coding examples on topics such as Web services, ASP.NET, ADO.NET, and Visual Studio .NET.

Automatically sign up today!

The Add and Insert methods accept parameters to define the
following properties:

  • A
    string value for the item’s key (used to access the item).
  • The
    actual object to store in the cache.
  • Set
    a dependency (via the CacheDependency object)
    that defines a condition that clears the cache when a particular
    dependency (file, directory, keys, or other objects) changes.
  • Define
    an absolute expiration date that sets when the object will expire and be
    removed from the cache. It accepts a DateTime
  • Define
    a sliding expiration date that specifies the amount of time (after an
    object is accessed last) to wait before an item is removed from the cache.
    It accepts a TimeSpan object.
  • Assign
    a priority to the item via a CacheItemPriority
    object. The legal values include NotRemovable,
    High, AboveNormal, Normal, BelowNormal,
    and Low.
  • Specify
    a delegate for a callback function to be notified when an item is removed.

Both the Add and Insert methods accept all of these
parameters, but the Insert method includes two overloaded signatures that
accept a subset of the list. The first signature accepts the key value and
actual object, while the other version accepts everything except the priority
and delegate. The Insert method is often used since the other parameters are
not used as often.

Working with the Cache

If you use the methods provided by the Cache class, it makes
it easy to utilize data caching in an application. The C# code in Listing A uses the cache to store a DataSet object. The DataSet
object is used to populate a DataGrid control on the
ASP.NET page. If the DataSet object is not found in
the cache, the database is queried. The Get method is used to check for its
existence in the cache before it is added.
Listing B contains the VB.NET equivalent.

Another detail you may notice is the need to convert the
object to its appropriate type when it is retrieved from the cache. This code
adds the object to the cache indefinitely. You may use the Insert or Add
methods to assign an expiration date to the item.

You could replace the Cache.Insert(“TestDS”, ds) from the previous code listings with the line in
Listing C
to set it to expire in 30 minutes.
Listing D contains the VB.NET version. On the other hand, you could use a sliding expiration window
with the line in
Listing E. The VB.NET version is in
Listing F. You may notice this second line uses a normal priority, but
it is no different since normal and default are the same.

Cache dependencies

One of the more interesting features is tying the cache to
an external source like a file. Cache dependencies allow you to make a cached
item dependent on another resource so that when the resource changes the cached
item is removed automatically. The dependent item may be other cache items, a
system file, or folder.

Using a cache dependency requires an instance of the CacheDependency object that points to the item used. The
VB.NET snippet in
Listing G creates such an object that points to a local file.

A great feature of ASP.NET 2.0 is the addition of a SQL
Server query as a cache dependency. Prior to this enhancement, developers often
utilize files and database triggers with the trigger writing to the file when a
data source changes.

Using the Response object

Accessing the Response.Cache
object returns an instance of the HttpCachePolicy class. This class contains methods for
setting cache-specific HTTP headers and controlling the ASP.NET page output
cache. The following list contains some of the available methods:

  • SetCacheability: sets the Cache-Control HTTP
    header. The Cache-Control HTTP header controls how documents are to be
    cached on the network.
  • SetNoServerCaching: stops all origin server caching for the current response.
  • SetVaryByCustom: specifies a custom text string
    to vary cached output responses by.
  • SetSlidingExpiration: sets cache expiration to
    sliding. When cache expiration is set to sliding, the Cache-Control HTTP
    header will be renewed with each response. This expiration mode is
    identical to the IIS configuration option to add an expiration header to
    all output set relative to the current time.

Data reuse via caching

Any Web application with a sizable group of users should
utilize caching to reduce the number of calls for data and, therefore, decrease
response time. ASP.NET provides programmatic access to the caching
functionality via the Caching API. It allows you to easily add items to the
cache, as well as manually remove items or automatically remove items using
expiration dates. Another feature allows you to tie an object’s lifetime to an
external resource like a system file.

Miss a column?

Check out the .NET Archive, and catch up on the most recent editions of Tony Patton’s column.

Tony Patton began his professional career as an application developer earning Java, VB, Lotus, and XML certifications to bolster his knowledge.

Subscribe to the Developer Insider Newsletter

From the hottest programming languages to commentary on the Linux OS, get the developer and open source news and tips you need to know. Delivered Tuesdays and Thursdays

Subscribe to the Developer Insider Newsletter

From the hottest programming languages to commentary on the Linux OS, get the developer and open source news and tips you need to know. Delivered Tuesdays and Thursdays