16.9. Caching Data Sources

Problem

You are using data sources in your application and you would like to cache the data source to improve the performance of your application.

Solution

Set the EnableCaching property of the data source to True and set the CacheDuration property to the desired expiration time:


	dSource.EnableCaching = True
	dSource.CacheDuration = 5


	dSource.EnableCaching = true;
	dSource.CacheDuration = 5;

Discussion

The data sources available in ASP.NET 2.0 (XmlDataSource, ObjectDataSource, and SqlDataSource) provide built-in support for caching. By using this built-in support, the data source will automatically cache the data it pulls from the data store. In other words, you do not need to handle the insertion and retrieval of the data source in the Cache explicitly, which simplifies the code in your application.

To use the built-in caching support in data sources, you need to set a couple of properties. First, you need to set the EnableCaching property to True to enable the caching of the data source.

Next, you need to define when the cached data expires by setting the CacheDuration property to the number of seconds after which the cached data is invalidated.

Optionally, you can set the CacheExpirationPolicy property to alter the way the CacheDuration time is used to cause the ...

Get ASP.NET 2.0 Cookbook, 2nd Edition 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.