O'Reilly logo

ASP.NET 2.0 Cookbook, 2nd Edition by Geoffrey T. LeBlond, Michael A Kittel

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

16.7. Caching Application Data

Problem

Your application draws on data that is expensive to create from a performance perspective, so you want to store it in memory to be accessed by users throughout the lifetime of the application. The problem is that the data changes occasionally and you need to refresh the data after it changes.

Solution

Place the data in the Cache object with a dependency set to the source of the data so the data will be reloaded when it changes. Examples 16-5 and 16-6 show the code we’ve written to demonstrate this solution. In this case, we have created a class, CH16CacheService, with methods that place some sample XML book data in the Cache object. In our example, the book data is automatically removed from the cache any time the XML file is changed.

Discussion

The Cache object in ASP.NET provides the ability to store application data in a manner similar to the storing of data in the Application object. The Cache object, unlike the Application object, lets you specify that the cached data is to be replaced at a specified time or whenever there is a change to the original source of the data.

Examples 16-5 (VB) and 16-6 (C#) show the CH16CacheService class with two methods we created for this example. The first method (getBookData) provides access to the data stored in the Cache object with the appropriate checking (to ensure the data is still valid) and reloading as required. The getBookData method performs the following operations:

  1. Gets a reference to the book data ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required