9.3. Caching Data


Given a Web Forms application that is performing poorly because it is repeatedly reading data that doesn’t change very often, you need to cache the data to eliminate unnecessary queries and improve the performance.


Use the ASP.NET Cache class.

The Web Forms page defines the data grid used to display the contents of a DataSet, a button to clear the cache, and a label that displays whether the data was retrieved from the cache or from the database. The code for the Web Forms page is shown in Example 9-3.

Example 9-3. File: ADOCookbookCS0903.aspx

<form id="ADOCookbookCS0903" method="post" runat="server">
    <asp:HyperLink id="HyperLink1"
        style="Z-INDEX: 101; LEFT: 16px; POSITION: absolute; TOP: 24px"
        runat="server" NavigateUrl="default.aspx">Main Menu
    <asp:DataGrid id="customersDataGrid"
        style="Z-INDEX: 102; LEFT: 16px; POSITION: absolute; TOP: 128px"
        runat="server" AllowPaging="True">
        <HeaderStyle Font-Bold="True"></HeaderStyle>
    <asp:Label id="cacheStatusLabel"
        style="Z-INDEX: 103; LEFT: 16px; POSITION: absolute; TOP: 96px"
        runat="server" ForeColor="Green"></asp:Label>
    <asp:Button id="clearCacheButton"
        style="Z-INDEX: 104; LEFT: 16px; POSITION: absolute; TOP: 56px"
        runat="server" Text="Clear Cache">

The code-behind contains three event handlers and two methods:


Checks the cache for an object with the key CustomerDataSet. If an entry is not found, the DataSet is loaded by calling the LoadDataSet( ...

Get ADO.NET Cookbook now with O’Reilly online learning.

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