ASP.NET

Caching Content

As you surf the Web, you see all manner of pages. Some sites churn their content very quickly, while others change much more slowly. Some pages have portions that change while other portions of the page remain static. If you have a page whose content changes infrequently, you may cache the output instead of regenerating it every time a request comes in.

At the outset, turning on output caching is easy. To set up caching, place the OutputCache directive on the page. It's a separate directive, like the Page directive. The OutputCache directive enables caching and provides certain control over its behavior. The following exercise introduces caching output.

Create a Cacheable Page

  1. Create a new Web site named OutputCaching.

  2. Open the Default.aspx file and insert the OutputCache directive near the top, immediately after the Page directive. For now, set the Trace attribute to false (we'll turn it on a bit later when we look at caching User Controls). At the very least, the OutputCache directive needs two things: (1) the Duration attribute to be set, and (2) the VaryByParam attribute to "none." We'll see more about these attributes shortly. The Duration attribute specifies how long the content should be cached. The VaryByParam attribute is for managing caching multiple versions of the page. The following listing shows the syntax of the OutputCache directive. This example caches the page's content for 15 seconds. The code following the output directive was generated by Visual Studio.

    <%@ Page Language="C#" AutoEventWireup="true"
    CodeFile="Default.aspx.cs" Inherits="_Default" trace="false"%>
    <%@ OutputCache Duration="15" VaryByParam="none" %>
    
    <!DOCTYPE html PUBLIC
    "-//W3C//DTD XHTML 1.1//EN"
    "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
    
    <html xmlns="http://www.w3.org/1999/xhtml" >
    <head runat="server">
        <title>Untitled Page</title>
    </head>
    <body>
        <form id="form1" runat="server">
        <div>
        </div>
        </form>
    </body>
    </html>
    
  3. Update the Page_Load method to print the date and time that this page was generated, like so:

    using System;
    using System.Data;
    using System.Configuration;
    using System.Web;
    using System.Web.Security;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using System.Web.UI.WebControls.WebParts;
    using System.Web.UI.HtmlControls;
    
    public partial class _Default : System.Web.UI.Page
    {
       protected void Page_Load(object sender, EventArgs e)
       {
          Response.Write("This page was generated and cached at: " +
             DateTime.Now.ToString());
       }
    }
    

    The first time the content is produced, the Page_Load method runs and produces the following output:

    Graphic

    No matter now many times you refresh the browser (you may do this by pressing F5 while running Internet Explorer within 15 seconds of first accessing the page), ASP.NET will grab the cached content and display that. As soon as 15 seconds has expired, ASP.NET runs the page in the normal way, calling Page_Load, regenerating the content, and caching it again. The following graphic illustrates the new page accessed just moments later than 15 seconds following the first hit:

    Graphic
  4. To get an idea as to how caching content might improve performance, add a small amount of code to the Page_Load method to put the executing thread to sleep for perhaps 10 seconds (this is to simulate an expensive content-generating routine). You'll need to use the System.Threading namespace to access the threading functions.

    using System;
    using System.Data;
    using System.Configuration;
    using System.Web;
    using System.Web.Security;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using System.Web.UI.WebControls.WebParts;
    using System.Web.UI.HtmlControls;
    using System.Threading;
    
    public partial class _Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
          Thread.Sleep(10000);
          Response.Write("This page was generated and cached at: " +
             DateTime.Now.ToString());
        }
    }
    
  5. Now surf to the page. Notice how long the page took to load (about 10 seconds). Immediately refresh the page. Notice the browser displays the content right away-without the long wait time. For pages that are expensive to generate and that don't change very often, caching the content represents an enormous performance boost for your Web site-especially as the number of clients increases.