16.7. Caching Application Data
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.
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.
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:
Gets a reference to the book data ...