Share via


Walkthrough: Caching Application Data in ASP.NET

Caching enables you to store data in memory for rapid access. Applications can access the cache and not have to retrieve the data from the original source whenever the data is accessed. This avoids repeated queries for data, and it can improve performance and scalability. In addition, caching makes data available when the data source is temporarily unavailable.

The .NET Framework provides classes that enable you to use caching facilities in ASP.NET applications. These classes are defined in the System.Runtime.Caching namespace.

Note

The System.Runtime.Caching namespace is new in the .NET Framework 4. This namespace makes caching is available to all .NET Framework applications.

This walkthrough shows you how to use the caching functionality that is available in the .NET Framework as part of an ASP.NET application. In the walkthrough, you cache the contents of a text file.

Tasks illustrated in this walkthrough include the following:

  • Creating an ASP.NET Web site.

  • Adding a reference to the .NET Framework 4.

  • Adding a cache entry that caches the contents of a file.

  • Providing an eviction policy for the cache entry.

  • Monitoring the path of the cached file, and notifying the cache of changes to the monitored items.

Prerequisites

In order to complete this walkthrough, you will need:

  • Microsoft Visual Studio 2010.

  • A text file that contains a small amount of text. You will display the contents of this text file in a Web page.

Creating an ASP.NET Web Site

You will start by creating an ASP.NET Web site.

Warning

This walkthrough uses a Web site project. You could use a Web application project instead. For information about the difference between these Web project types, see Web Application Projects versus Web Site Projects.

To create an ASP.NET Web site

  1. Start Visual Studio 2010.

  2. In the File menu, click New Web Site. (If you do not see this option, click New, and then click Web Site.)

    The New Web Site dialog box is displayed.

  3. Under Installed Templates, click Visual Basic or C# and then select ASP.NET Web Site.

  4. In the Web Location box, select File System and enter the name of the folder where you want to keep the pages of the Web site. For example, enter the folder name C:\Websites\AppCaching and then click OK.

    Visual Studio creates a Web project that includes prebuilt functionality for layout (a master page, the Default.aspx and About.aspx content pages, and a cascading style sheet), for Ajax (client script files), and for authentication (ASP.NET membership). When a new page is created, by default Visual Web Developer displays the page in Source view, where you can see the page's HTML elements.

The next step is to add the text file you want to use to the current Web site project.

To add the text file to the project

  1. In Solution Explorer, right-click the name of the project and then click Add Existing Item.

  2. In the Add Existing Item dialog box, select the text file that you want to use for this walkthrough, and then click Add.

Adding a Reference to the Caching Assembly

To use the System.Runtime.Caching namespace in an ASP.NET application, you must add a reference to the namespace.

To add a reference the Website

  1. In Solution Explorer, right-click the name of the Web site and then click Add Reference.

  2. Select the .NET tab, select System.Runtime.Caching, and then click OK.

Adding Controls to the ASP.NET Page

The next step is to add a button and a Label control to the page. You will create an event handler for the button's Click event. Later you will add code to so when you click the button, the cached text is displayed in the Label control.

To add controls to the page

  1. Open or switch to the Default.aspx page.

  2. From the Standard tab of the Toolbox, drag a Button control to the Default.aspx page.

  3. In the Properties window, set the Text property of the Button control to Get From Cache. Accept the default ID property.

  4. From the Standard tab of the Toolbox, drag a Label control to the page. Accept the default ID property.

Creating the Cache and Caching an Entry

Next, you will add the code to perform the following tasks:

  • Create an instance of the cache class—that is, you will instantiate the cache object.

  • Specify that the cache uses a HostFileChangeMonitor object to monitor changes in the text file.

  • Read the text file and cache its contents as a cache entry.

  • Display the contents of the cached text file.

To create the cache object

  1. Double-click the button to create an event handler in the Default.aspx.cs or Default.aspx.vb file.

  2. At the top of the file (before the class declaration), add the following Imports (Visual Basic) or using (C#) statements.

    [Visual Basic]

    Imports System.Runtime.Caching
    Imports System.IO
    

    [C#]

    using System.Runtime.Caching;
    using System.IO;
    
  3. In the event handler, add the following code to instantiate the cache.

    [Visual Basic]

    Dim cache As ObjectCache = MemoryCache.Default
    

    [C#]

    ObjectCache cache = MemoryCache.Default;
    

    The ObjectCache is a base class that provides methods for implementing an in-memory cache object.

    Note

    In ASP.NET 4, caching is implemented by using the ObjectCache class.

  4. Add the following code to read the contents of a cache entry named filecontents

    [Visual Basic]

    Dim fileContents As String = TryCast(cache("filecontents"), String)
    

    [C#]

    string fileContents = cache["filecontents"] as string;
    
  5. Add the following code to check whether the cache entry named filecontents exists

    [Visual Basic]

    If fileContents Is Nothing Then
    
    End If
    

    [C#]

    if (fileContents == null)
    {
    
    }
    

    If the specified cache entry does not exist, you must read the text file and add it as a cache entry to the cache.

  6. In the if/then block, add the following code to create a new CacheItemPolicy object that specifies that the cache expires after 10 seconds.

    [Visual Basic]

    Dim policy As New CacheItemPolicy()
    policy.AbsoluteExpiration = DateTimeOffset.Now.AddSeconds(10.0)
    

    [C#]

    CacheItemPolicy policy = new CacheItemPolicy();
    policy.AbsoluteExpiration = DateTimeOffset.Now.AddSeconds(10.0);
    

    If no eviction or expiration information is provided, the default is InfiniteAbsoluteExpiration, which means that items in the cache do not expire based on an absolute time. Instead, items expire only when there is memory pressure. As a best practice, you should always explicitly provide either an absolute or a siding expiration. In this walkthrough, you use an absolute expiration of 10 seconds.

  7. Inside the if/then block and following the code you added in the previous step, add the following code to create a collection for the file paths that you want to monitor and to add the path of the text file to the collection.

    [Visual Basic]

    Dim filePaths As New List(Of String)()
    Dim cachedFilePath As String = Server.MapPath("~") & _
            "\cacheText.txt"
    filePaths.Add(cachedFilePath)
    

    [C#]

    List<string> filePaths = new List<string>();
    string cachedFilePath = Server.MapPath("~") + "\\cacheText.txt";
    filePaths.Add(cachedFilePath);
    

    The HttpServerUtilityMapPath() method returns the path to the root of the current Web site.

  8. Following the code you added in the previous step, add the following code to add a new HostFileChangeMonitor object to the collection of change monitors for the cache entry.

    [Visual Basic]

    policy.ChangeMonitors.Add(New HostFileChangeMonitor(filePaths))
    

    [C#]

    policy.ChangeMonitors.Add(new HostFileChangeMonitor(filePaths));
    

The HostFileChangeMonitor object monitors the text file's path and notifies the cache if changes occur. In this example, the cache entry will automatically expire if the contents of the file changes.

  1. Following the code you added in the previous step, add the following code to read the contents of the text file.

    fileContents = File.ReadAllText(cachedFilePath) & vbCrLf & DateTime.Now.ToString()
    
    fileContents = File.ReadAllText(cachedFilePath) + "\n" + DateTime.Now; 
    

    The date and time timestamp is added to help you determine when the cache entry expires.

  2. Following the code you added in the previous step, add the following code to insert the contents of the file into the cache object as a CacheItem instance.

    [Visual Basic]

    cache.Set("filecontents", fileContents, policy)
    

    [C#]

    cache.Set("filecontents", fileContents, policy);
    

    You specify information about how the cache entry should be evicted by passing the CacheItemPolicy object as a parameter Set method.

  3. After the if/then block, add the following code to display the cached file content in a Label control.

    [Visual Basic]

    Label1.Text = fileContents
    

    [C#]

    Label1.Text = fileContents;
    

Testing Caching in the ASP.NET Web Site

You can now test the application.

To test caching in the ASP.NET Web site

  1. Press CTRL+F5 to run the application.

  2. Click Get From Cache.

    The cached content in the text file is displayed in the label. Notice the timestamp at the end of the file.

  3. Click Get From Cache again.

    The timestamp is unchanged. This indicates the cached content is displayed.

  4. Wait 10 seconds or more and then click Get From Cache again.

    This time a new timestamp is displayed. This indicates that the policy let the cache expire after 10 seconds and that new cached content is displayed.

  5. In a text editor, open the text file that you added to the Web site project. Do not make any changes yet.

  6. Click Get From Cache again.

    Notice the time stamp again.

  7. Make a change to the text file and then save the file.

  8. Click Get From Cache again.

    This time the timestamp changes immediately. This indicates that the host-file change monitor evicted the cache item immediately when you made a change.

    Note

    You can increase the eviction time to 20 seconds or more to allow more time for you to make a change in the file.

Code Example

After you have completed this walkthrough, the code for the Web site you created will resemble the following example.

Imports System.Runtime.Caching
Imports System.IO

Partial Class _Default
    Inherits System.Web.UI.Page

    Protected Sub Button1_Click(ByVal sender As Object, _
            ByVal e As System.EventArgs) Handles Button1.Click
        Dim cache As ObjectCache = MemoryCache.Default
        Dim fileContents As String = TryCast(cache("filecontents"), _
            String)
        If fileContents Is Nothing Then
            Dim policy As New CacheItemPolicy()
            policy.AbsoluteExpiration = _
                DateTimeOffset.Now.AddSeconds(10.0)
            Dim filePaths As New List(Of String)()
            Dim cachedFilePath As String = Server.MapPath("~") & _
                "\cacheText.txt"
            filePaths.Add(cachedFilePath)
            policy.ChangeMonitors.Add(New  _
                HostFileChangeMonitor(filePaths))

            ' Fetch the file contents.
            fileContents = File.ReadAllText(cachedFilePath) & _
                vbCrLf & DateTime.Now.ToString()
            cache.Set("filecontents", fileContents, policy)
        End If
        Label1.Text = fileContents
    End Sub

End Class
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Runtime.Caching;
using System.IO;

public partial class _Default : System.Web.UI.Page
{


    protected void Button1_Click1(object sender, EventArgs e)
    {
        ObjectCache cache = MemoryCache.Default;
        string fileContents = cache["filecontents"] as string;

        if (fileContents == null)
        {
            CacheItemPolicy policy = new CacheItemPolicy();
            policy.AbsoluteExpiration =
                DateTimeOffset.Now.AddSeconds(10.0);

            List<string> filePaths = new List<string>();
            string cachedFilePath = Server.MapPath("~") +
                "\\cacheText.txt";

            filePaths.Add(cachedFilePath);

            policy.ChangeMonitors.Add(new
                HostFileChangeMonitor(filePaths));

            // Fetch the file contents.
            fileContents = File.ReadAllText(cachedFilePath) + "\n"
                + DateTime.Now.ToString();

            cache.Set("filecontents", fileContents, policy);

        }

        Label1.Text = fileContents;
    }
}

Next Steps

In ASP.NET, you can use multiple cache implementations to cache data. For more information, see Caching Application Data by Using Multiple Cache Objects in an ASP.NET Application.

See Also

Reference

MemoryCache

ObjectCache

Concepts

Caching in .NET Framework Applications