Object Caching

All the examples in the preceding section have cached pages, or parts of pages wrapped in user controls. But ASP.NET allows you much more caching flexibility. You can use object caching to place any object in the cache. The object can be of any type: a data type, a web control, a class, a DataSet, and so on.

The object cache is stored in server memory, a limited resource, and the careful developer will conserve that resource. With that said, it is an easy way to buy significant performance benefits when used wisely, especially because ASP.NET will evict older items if memory becomes scarce.

Suppose you are developing a retail shopping catalog web application. Many of the page requests contain queries against the same database to return a relatively static price list and description data. Instead of your control querying the database each time the data is requested, the data set is cached, so subsequent requests for the data will be satisfied from the high-speed cache rather than forcing a relatively slow and expensive regeneration of the data. You might want to set the cache to expire every minute, every hour, or every day, depending on the needs of the application and the frequency with which the data is likely to change.

Object caching is implemented by the Cache class. One instance of this class is created automatically per application when the application starts. The class remains valid for the life of the application. The Cache class uses syntax very similar to ...

Get Programming ASP.NET 3.5, 4th Edition now with the O’Reilly learning platform.

O’Reilly members experience live online training, plus books, videos, and digital content from nearly 200 publishers.