9.3. Caching Data
Problem
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.
Solution
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:HyperLink>
<asp:DataGrid id="customersDataGrid"
style="Z-INDEX: 102; LEFT: 16px; POSITION: absolute; TOP: 128px"
runat="server" AllowPaging="True">
<HeaderStyle Font-Bold="True"></HeaderStyle>
</asp:DataGrid>
<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">
</asp:Button>
</form>The code-behind contains three event handlers and two methods:
Page.LoadChecks the cache for an object with the key
CustomerDataSet. If an entry is not found, theDataSetis loaded by calling theLoadDataSet( ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access