13.6. 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, where it can 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 when 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. Example 13-3 and Example 13-4 show the code we’ve written to demonstrate this solution. In this case, these are VB and C# code-behind files for Global.asax that place some sample XML book data in the Cache object. In our example, the book data is automatically removed from the cache anytime 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.

In Example 13-3 and Example 13-4, two methods have been added to global.asax.vb (or global.asax.cs for C#). 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 ...

Get ASP.NET Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.