10.7. 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 solution has a Web Form that 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 C# code for the Web Forms page Default.aspx in the project CachingData
is shown in Example 10-10.
Example 10-10. File: Default.aspx for CachingData solution
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="CachingData.Default" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title>Untitled Page</title> </head> <body> <form id="form1" runat="server"> <br /> <asp:Button ID="clearCacheButton" runat="server" Text="Clear Cache" OnClick="clearCacheButton_Click" /> <br /> <asp:Label ID="cacheStatusLabel" runat="server" ForeColor="Green" /> <br /> <asp:GridView ID="departmentGridView" runat="server" AllowPaging="True" OnPageIndexChanging="departmentGridView_PageIndexChanging"> <HeaderStyle Font-Bold="True"></HeaderStyle> </asp:GridView> </form> </body> </html>
The code-behind for the page checks the Cache
for a DepartmentDataSet ...
Get ADO.NET 3.5 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.