Export (0) Print
Expand All

How to: Cache Page Output with Cache Key Dependencies

At times, you might want to remove a page from the output cache when another item in the cache is removed. For example, you might have a page that displays a process-intensive report that is placed in the application cache and used by multiple pages. When the report is changed or is removed from cache, you want the page output to be removed from the cache also because the report is no longer valid. To do this you can make cached page output dependent on other cached items.

NoteNote

You can explicitly remove any page from the output cache by calling the RemoveOutputCacheItem method. You can do this from the Global.asax file, from a custom ASP.NET server control, or from a page, depending on the needs of your application.

To make cached page output dependent upon another cache item

  1. In a page, specify cache settings either declaratively or programmatically. For more information, see How to: Set Expiration Values for ASP.NET Page Caching, Setting the Cacheability of a Page, and Caching Multiple Versions of a Page.

  2. In page code, call the AddCacheItemDependency method. As the cacheKey parameter, pass the name of the cache item on which to create a dependency.

    The following code example shows how to set a dependency on the item named ProcessIntensiveReport. When this item is modified or removed, the page output will be removed from the cache.

    protected void Page_Load(object sender, EventArgs e)
    {
        Response.AddCacheItemDependency("ProcessIntensiveReport");
    
        // Set additional properties to enable caching.
        Response.Cache.SetExpires(DateTime.Now.AddSeconds(60));
        Response.Cache.SetCacheability(HttpCacheability.Public);
        Response.Cache.SetValidUntilExpires(true);
    }
    

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Response.AddCacheItemDependency("ProcessIntensiveReport")
    
        ' Set additional properties to enable caching.
        Response.Cache.SetExpires(DateTime.Now.AddSeconds(60))
        Response.Cache.SetCacheability(HttpCacheability.Public)
        Response.Cache.SetValidUntilExpires(True)
    End Sub
    
    NoteNote

    You cannot call the AddCacheItemDependency method in an ASP.NET user control. However, in any user control that specifies the @ OutputCache directive, you can create a CacheDependency object that describes the cache key dependency and assign it to the Dependency property of the UserControl object.

See Also

Community Additions

ADD
Show:
© 2014 Microsoft