Export (0) Print
Expand All

Walkthrough: Using Multiple Cache Objects in an ASP.NET Application

.NET Framework 4

ASP.NET lets you use multiple cache instances in an ASP.NET Web site application—that is, you can instantiate different cache classes and store data in the different instances. You can use different cache instances to cache the same data, or you can use different cache instances to cache different data. For example, for one cache instance, you might let the cache use as much memory as possible, but for the other implementation, you might specify a maximum amount of memory that the cache can use.

This walkthrough shows you how to use different instances of the memory cache object in the same ASP.NET application in order to cache the contents of different text files. For one text file, you will use the built-in in-memory cache object. For this cache, you will allow the cache to expire every 10 seconds or when the file is changed, whichever comes first. For the second text file, you will use a custom cache class that inherits from the built-in memory class. The custom class demonstrates how you would store the cached data in a named region, which is a partition in memory that is reserved for storing one or more cache objects. A cache region helps organize cache objects in memory. The built-in memory cache object does not support the concept of regions but it is used in this walkthrough to demonstrate how you would implement regions in a custom cache class.

NoteNote

Although the built-in memory cache object does not support regions, the regions partition concept is used with the built-in memory cache class in this walkthrough for demonstration only.

Tasks illustrated in this walkthrough include the following:

  • Creating an ASP.NET Web site.

  • Adding a reference to the .NET Framework.

  • Adding a cache class that caches the contents of a text file by using the built-in memory cache object.

  • Adding a cache implementation that caches the contents of a text file by using a custom cache object.

  • Adding data to each cache.

  • Testing the cache.

In order to complete this walkthrough, you will need:

  • Microsoft Visual Studio 2010 or Microsoft Visual Web Developer Express.

  • Two text files, each containing a small amount of text. You will display the contents of the text files in a Web page.

You will start by creating an ASP.NET Web site. If you have created a Web site by using Microsoft Visual Studio 2010, you can use that Web site and skip this step.

To create an ASP.NET Web site

  1. Start Microsoft Visual Studio 2010 or Microsoft Visual Web Developer Express2010.

  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\MultipleCaching and then click OK.

    Visual Studio creates the folder and opens the Web site in Source view. Notice that the root Web site contains several files and folders including the Account folder, a Web.config file, the About.aspx and Default.aspx pages, and the Site.master master page.

The next step is to add the text files 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 to add one text file.

  3. Repeat the steps to add the second text file.

To use the caching classes that are defined in the System.Runtime.Caching namespace in an ASP.NET application, you must add a reference to that namespace in your project.

To add a reference the caching assemblies

  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.

    A reference to the assembly is added to the project so that you can use classes in the System.Runtime.Caching namespace.

To illustrate how to use caching, you will display the content of the text files on a page in a way that lets you see whether the contents have been cached or are being read from the file. To do this, you will add create code that reads the contents of the text files and caches them. In this procedure, you add controls to the page that will let you display cache and display the text files.

To add controls to the page

  1. From the Standard tab of the Toolbox, drag two Button controls to the Default.aspx page.

  2. In the Properties window, set the Text property of one of the Button controls to Get from Built-In Cache. Accept the default ID property.

  3. Set the Text property of the other Button control to Get from Custom 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.

Next, you will add code to create an instance of the built-in cache object. The built-in cache object caches data in memory. The code will perform the following tasks:

  • Create an instance of the MemoryCache class.

  • Specify that the cache uses a HostFileChangeMonitor object to monitor changes in one of the text files that you are using in this walkthrough.

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

  • Display the contents of the cached text file.

To create an instance of the built-in memory cache object

  1. Double-click the Get from Built-In Cache 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 using (C#) or Imports (Visual Basic) statements.

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

    ObjectCache cache = MemoryCache.Default;
    

    The ObjectCache class provides an in-memory object cache.

    NoteNote

    The ObjectCache class is a replacement for the Cache class that was used in earlier versions of ASP.NET. In ASP.NET 4, the preferred way to implement caching it to use the ObjectCache class.

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

    string fileContents = cache["filecontents"] as string;
    
  5. Add code to perform the following tasks:

    • Check whether the cache entry named filecontents exists. If the specified cache entry does not exist, read the text file and add it as a cache entry to the cache.

    • Create a new CacheItemPolicy object that specifies that the cache entry expires after 10 seconds.

    • Create a collection for the file paths you want to monitor and add the path of the text file to the collection.

    • Add a new HostFileChangeMonitor object to the collection of change monitors for the cache entry. The HostFileChangeMonitor object monitors the text file's path and notifies the cache if changes occur. For this walkthrough, you will configure the change monitor so that the cache entry will automatically expire if the contents of the file changes.

    • Read the contents of the text file.

    • Insert the contents of the file into the cache object as a CacheItem instance. You specify information about how the cache entry should be evicted by passing the CacheItemPolicy object as a parameter in the Set method.

      The following example shows code that accomplishes these tasks.

      if (fileContents == null)
      {
          CacheItemPolicy policy = new CacheItemPolicy();
                  policy.AbsoluteExpiration = 
                  DateTimeOffset.Now.AddSeconds(10.0);
      
                  List<string> filePaths = new List<string>();
                  string cachedFilePath = Server.MapPath("~") + "\\cachedText.txt";
                  filePaths.Add (cachedFilePath);
      
                  policy.ChangeMonitors.Add(new 
                  HostFileChangeMonitor(filePaths));
      
                  // Fetch the file contents.
                  fileContents =
                  File.ReadAllText(cachedFilePath) + "\n" +
                      " Using built-in cache " + "\n" + DateTime.Now.ToString();
                      
                  cache.Set("filecontents", fileContents, policy);
      }
      
      
  6. Add the following code to display the cached file content in a Label control.

    Label1.Text = fileContents;
    

Next, you will create a custom cache class named CustomCache. In this example, the custom class will inherit from the build-in MemoryCache class. You will override the base class's methods in order to provide a custom implementation. You can use the API in the System.Runtime.Caching namespace to implement region partitions in a cache class that supports regions. For example, if your custom class inherits from a cache class that supports regions, such as the Windows Azure caching, your custom class will support creating cache objects with region partitions. The built-in memory cache object does not support the concept of regions partitions but it is used in this walkthrough to demonstrate how you would implement region partitions in a custom cache class. Overloads of the set methods provide different ways to add a cache item to the cache. A cache item can be added by specifying the cache item, an expiration policy, a key/value pair named region in memory where the cache should be stored and so on.

To create the custom cache class

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

    The New Item dialog box is displayed.

  2. Under Installed Templates, select Visual Basic or Visual C# and the select Class.

  3. In the Name text box, enter the name CustomCache and then click Add.

  4. In the dialog box that appears, click Yes to put the class in the App_Code folder.

  5. In the code editor, replace the contents of the class file with the following code:

    using System;
    using System.Web;
    using System.Runtime.Caching;
    
    namespace CustomCacheSample
    {
        public class CustomCache : MemoryCache
        {
            public CustomCache() : base("defaultCustomCache") { }
    
            public override void Set(CacheItem item, CacheItemPolicy policy)
            {
                Set(item.Key, item.Value, policy, item.RegionName);
            }
    
            public override void Set(string key, object value, DateTimeOffset absoluteExpiration, string regionName = null)
            {
                Set(key, value, new CacheItemPolicy { AbsoluteExpiration = absoluteExpiration }, regionName);
            }
    
            public override void Set(string key, object value, CacheItemPolicy policy, string regionName = null)
            {
                base.Set(CreateKeyWithRegion(key, regionName), value, policy);
            }
    
            public override CacheItem GetCacheItem(string key, string regionName = null)
            {
                CacheItem temporary = base.GetCacheItem(CreateKeyWithRegion(key, regionName));
                return new CacheItem(key, temporary.Value, regionName);
            }
    
            public override object Get(string key, string regionName = null)
            {
                return base.Get(CreateKeyWithRegion(key, regionName));
            }
    
            public override DefaultCacheCapabilities DefaultCacheCapabilities
            {
                get
                {
                    return (base.DefaultCacheCapabilities | System.Runtime.Caching.DefaultCacheCapabilities.CacheRegions);
                }
            }
    
            private string CreateKeyWithRegion(string key, string region)
            {
                return "region:" + (region == null ? "null_region" : region) + ";key=" + key;
            }
        }
    }
    
    
  6. Save the file.

Next, you will instantiate the CustomCache class and create a custom memory cache object that adds the cache entry to a region. The code will perform the following tasks:

  • Create an instance of a custom cache class.

  • Specify a named region (a region in the cache to which a cache entry can be added). The path of the text file will not be monitored for changes. This means that the cache entry will not expire when the file is changed.

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

  • Display the contents of the cached text file.

To create an instance of the custom cache object and add a cache entry

  1. Switch to or open the Default.aspx file.

  2. Double-click the Get from Custom Cache button to create an event handler in the Default.aspx.cs or Default.aspx.vb file.

  3. At the top of the file (before the class declaration), add the following Imports (Visual Basic) or using (C#) statements to add the namespace that the custom class is in.

    using CustomCacheSample;
    
  4. Inside the class declaration (for the partial class _Default) but outside of the existing event handler, add the following code to instantiate the custom cache. You must create and keep the reference of the custom cache to prevent it from going out of scope.

    private static ObjectCache customCache = 
        new CustomCache();
    private ObjectCache RegionCache { get { return customCache; } }
    
  5. In the event handler for the Click event of Button2, add the following code to read the contents of a cache entry named CustomFilecontents from the RegionCache cache.

    string CustomFileContents = RegionCache.Get("filecontents", "Region_A") as string;
    
    
  6. Add code to perform the following tasks:

    • Check whether the cache entry named filecontents exits. If the specified cache entry does not exist, you must read the text file and add it as a cache entry to the cache.

    • Read the text file.

    • Insert the contents of the file into the custom cache object as a cache entry. You specify the named region where the cache entry should be added by passing the region name as parameter in the Set method. You also specify that the cache should not expire based on an absolute time by passing the InfiniteAbsoluteExpiration field as a parameter in the Set method. Instead, items will expire only when there is memory pressure.

      The following example shows how to accomplish these tasks.

      NoteNote

      The "Using custom cache" string is added to the text of the text file to help you identify the cached data when you test the page later in this walkthrough.

      if (CustomFileContents == null)
      {
          //Fetch the file contents
          string cachedFilePath = Server.MapPath("~") + "\\cachedText.txt";
          CustomFileContents = File.ReadAllText(cachedFilePath) + 
             " Using custom cache " + "\n" + DateTime.Now.ToString();
                   
          // For this cache region, do not bind a file-change monitor.
          // The cache will not expire based on absolute time.
          RegionCache.Set("filecontents", CustomFileContents, ObjectCache.InfiniteAbsoluteExpiration, "Region_A");
      
      }
      
  7. Add the following code to display the cached file content in a Label control.

    Label1.Text = CustomFileContents
    
    Label1.Text = CustomFileContents;
    

You can now test caching.

To test caching

  1. Press CTRL+F5 to run the application.

  2. Click Get from Built-in Cache.

    The cached content in the text file is displayed in the label. Notice the "Using built-in cache" statement and the time stamp at end of the file.

  3. Click Get from Built-in Cache again.

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

  4. Wait 10 seconds or more and then click Get from Built-in Cache again.

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

  5. Click Get from Custom Cache.

    The cached content in the text file is displayed in the label. Notice the "Using custom cache" statement and the time stamp at the end of the file.

  6. Click Get from Custom Cache again. The timestamp is unchanged. This indicates the cached content is displayed.

  7. Wait 10 seconds or more and then click Get from Custom Cache again. The timestamp is still unchanged. This indicates that the cache does not expire based on a policy. However, when the server starts run low on memory, the cache will automatically expire.

Community Additions

ADD
Show:
© 2014 Microsoft