Compartilhar via


ASP.NET Caching Overview

An application can often increase performance by storing data in memory that is accessed frequently and that requires significant processing time to create. For example, if your application processes large amounts of data using complex logic and then returns the data as a report accessed frequently by users, it is efficient to avoid re-creating the report every time that a user requests it. Similarly, if your application includes a page that processes complex data but that is updated only infrequently, it is inefficient for the server to re-create that page on every request.

To help you increase application performance in these situations, ASP.NET provides caching using two basic caching mechanisms. The first is application caching, which allows you to cache data you generate, such as a DataSet object or a custom report business object. The second is page output caching, which saves the output of page processing and reuses the output instead of re-processing the page when a user requests the page again.

Application Cache

The application cache provides a programmatic way for you to store arbitrary data in memory using key/value pairs. Using the application cache is like using application state. However, unlike application state, the data in the application cache is volatile. This means it is not stored in memory for the life of the application. The advantage of using the application cache is that ASP.NET manages the cache and removes items when they expire or become invalidated, or when memory runs low. You can also configure application caching to notify your application when an item is removed. For more information, see Caching Application Data.

The pattern when using the application cache is to determine whether an item exists in the cache any time you access an item, and if it does, to use it. If the item does not exist, you can re-create the item and then place it back in the cache. This pattern ensures that you always have the latest data in the cache.

For more information, see Caching in .NET Framework Applications and How to: Retrieve Values of Cached Items.

Page Output Cache

A typical kind of caching for server applications is output caching. Output caching enables you to store rendered HTML. The stored HTML is served in response to subsequent requests for the same page. You can use output caching to cache a whole Web page or just the output of an ASP.NET control. Output caching enables you to do the following:

  • Configure ASP.NET to cache a particular output cache entry for a specific period.

  • Cache a different version of the content based on the browser type or user-language preferences of the clients visiting your application.

  • Cache a mobile version of a page that differs from a version that is optimized for a desktop browser.

  • Configure ASP.NET to evict a cache entries based on an external event.

Output caching is extensible. You can use a custom output cache provider that can store data on any data storage device.

The page output cache stores the contents of a processed ASP.NET page in memory. This lets ASP.NET send a page response to a client without going through the page processing life cycle again. Page output caching is especially useful for pages that do not change often but that require significant processing to create. For example, if you are creating a high-traffic Web page to display data that is not frequently updated, page output caching can dramatically increase the performance of that page. Page caching can be configured individually for each page, or you can create cache profiles in the Web.config file, which allow you to define caching settings once and then use those settings with multiple pages.

Page output caching provides two models for page caching: full-page caching and partial-page caching. Full-page caching persists the complete contents of a page and uses the cached page content to fulfill client requests. Partial-page caching persists specified portions of a page and lets other portions of the page be created dynamically. For more information, see Caching Portions of an ASP.NET Page.

Partial-page caching can work in two ways: control caching and post-cache substitution. Control caching, also sometimes referred to as fragment caching, lets you cache parts of the page output by including the information in a user control and then marking the user control as cacheable. This enables specific content throughout a page to be cached, while the overall page is not cached and is therefore re-created on each request. For example, if you create a page that displays largely dynamic content, such as stock information, but has sections that are static, such as weekly summaries, you can place the static sections in user controls and specify that they are cached.

Post-cache substitution is the opposite. The page as a whole is cached, but fragments within the page are dynamic. For example, if you create a page that is static for set periods of time, you can set the entire page to be cached. If you added a Label control to the page that displayed the user's name, the Label would stay the same for each page refresh and each user, showing the name of the user who requested that page before it was cached. However, with post-cache substitution, you can configure the page to be cached, but mark individual sections of the page as not cacheable. In this case, you could add the Label controls to a non-cacheable section and they would be dynamically created for each user and page request. For more information, see Caching Portions of an ASP.NET Page.

Caching Pages Based on Request Parameters

In addition to caching a single version of a page, ASP.NET page output caching provides features to create multiple versions of the page that vary by different request parameters. For more information, see Caching Multiple Versions of a Page.

Extensible Output Caching

ASP.NET adds extensibility to output caching that enables you to configure one or more custom output-cache providers. Output-cache providers can use any storage mechanism to persist HTML content. These storage options can include local or remote disks, cloud storage, and distributed cache engines.

Output-cache provider extensibility in ASP.NET lets you design more aggressive and more intelligent output-caching strategies for Web sites. For example, you can create an output-cache provider that caches the "Top 10" pages of a site in memory, while caching pages that get lower traffic on disk. Alternatively, you can cache every vary-by combination for a rendered page, but use a distributed cache so that the memory consumption is offloaded from front-end Web servers.

You create a custom output-cache provider as a class that derives from the OutputCacheProvider type. You can then configure the provider in the Web.config file by using the new providers subsection of the outputCache element, as shown in the following example:

<caching>
  <outputCache defaultProvider="AspNetInternalProvider">
    <providers>
      <add name="DiskCache" 
          type="Test.OutputCacheEx.DiskOutputCacheProvider, DiskCacheProvider"/>
    </providers>
  </outputCache>
</caching>

For more information and for examples that show how to configure the output cache, see outputCache Element for caching (ASP.NET Settings Schema). For more information about the classes that support caching, see the documentation for the OutputCache and OutputCacheProvider classes.

By default, all HTTP responses, rendered pages, and controls use the in-memory output cache that is illustrated in the previous example (where the defaultProvider attribute is set to AspNetInternalProvider). You can change the default output-cache provider that is used for a Web application by specifying a different provider name for defaultProvider.

You can also select different output-cache providers for individual control and for individual requests. The easiest way to choose a different output-cache provider for different Web user controls is to do so by declaratively using the providerName attribute in an @ Page or @ Control directive, as shown in the following example:

<%@ OutputCache Duration="60" VaryByParam="None" 
    providerName="DiskCache" %>

To specify a different output cache provider for an HTTP request, you override the new GetOutputCacheProviderName method in the Global.asax file to programmatically specify which provider to use for a specific request. For more information, see GetOutputCacheProviderName.

Automatic Data Removal

ASP.NET can remove data from the cache for one of these reasons:

  • Because memory on the server is low, a process known as scavenging.

  • Because the item in the cache has expired.

  • Because the item's dependency changes.

To help you manage cached items, ASP.NET can notify your application when items are removed from the cache.

Scavenging

Scavenging is the process of deleting items from the cache when memory is scarce. Items are removed when they have not been accessed in some time or when items are marked as low priority when they are added to the cache. ASP.NET uses the CacheItemPriority object to determine which items to scavenge first. For more information, see How to: Add Items to the Cache.

Expiration

In addition to scavenging, ASP.NET automatically removes items from the cache when they expire. When adding an item to the cache, you can set it to expire as described in the following table.

Expiration Type

Description

Sliding expiration

Specifies how long after an item was last accessed that it expires. For example, you can set an item to expire 20 minutes after it was last accessed in the cache.

Absolute expiration

Specifies that an item expires at a set time, regardless of how often it is accessed. For example, you can set an item to expire at 6:00 PM or after four hours.

Dependencies

You can configure an item's lifetime in the cache to be dependent on other application elements such as files or databases. When the element that a cache item depends on changes, ASP.NET removes the item from the cache. For example, if your Web site displays a report that the application creates from an XML file, you can place the report in the cache and configure it to have a dependency on the XML file. When the XML file changes, ASP.NET removes the report from the cache. When your code requests the report, the code first determines whether the report is in the cache, and if not, your code can re-create it. Therefore, an up-to-date version of the report is always available.

ASP.NET caching supports the dependencies described in the following table.

Dependency

Description

Key dependency

Items in the application cache are stored in key/value pairs. Key dependency allows an item to be dependent on the key of another item in the application cache. When the original item is removed, the item that has the key dependency is also removed. For example, you could add a cache item named ReportsValid, and then cache several reports that are dependent on the ReportsValid key. When the ReportsValid item is removed, all the dependent cached reports are similarly removed from the cache.

File dependency

An item in the cache is dependent on an external file. If the file is modified or deleted, the cached item is removed.

SQL dependency

An item in the cache is dependent on changes in a table in a Microsoft SQL Server 2005, SQL Server 2000, or SQL Server 7.0 database. For SQL Server 2005, an item can be dependent on a row in a table. For more information, see Caching in ASP.NET with the SqlCacheDependency Class.

Aggregate dependency

An item in the cache is dependent on multiple elements through the use of the AggregateCacheDependency class. If any of the dependencies change, the item is removed from the cache.

Custom dependency

An item in the cache is configured with a dependency that you create in your own code. For example, you can create a custom Web service cache dependency that removes data from the cache when a call to a Web service results in a particular value.

Application Cache Item Removal Notification

You can be notified when an item is removed from the application cache. For example, if you have an item that takes considerable amount of processing time to create, you can be notified when it is removed from the cache so that you can replace it immediately. As a result, the next time that the item is requested, the user does not have to wait for it to be processed. For more information, see How to: Notify an Application When an Item Is Removed from the Cache.

See Also

Tasks

How to: Cache Page Output with File Dependencies

Concepts

Caching ASP.NET Pages

Caching Application Data

Caching in ASP.NET with the SqlCacheDependency Class