Caching

Two types of caching

  • application - a collection that can store any object in memory. Removes objects based on memory or time limits
  • page - ASP.NET ability to store rendered pages, or portions thereof, to reduce time to render future requests.

For most sites biggest factor in performance is network latency.

Second biggest is number of individual objects that browsers need to load to display page. Minimised number of such objects by combining multiple style sheets and javascript files, using text links rather than images, etc.

If browser needs to load 6+ objects then distribute these between different hostnames to allow browser to request them simultaneously.

Minimise bandwidth requirements by reducing size of web pages. Enable http compression, minify javascript and compress images, sounds, videos, etc.

Application caching

Process of storing data (not pages) in a cache object.

Cache object is available as property of the Page object.

Acts as application wide cache - not just a page specific cache, i.e. single cache object exists for entire application. Items in cache can be shared between users sessions and requests.

Using cache object

Use like Session or similar objects.

Assign objects to cache using key, and retrieve using this key.

Always verify that retrieved items are not null - value either has not been cached, or has expired.

if (Cache["Greeting"] != null)
  Label1.Text = (String)Cach["Greeting"];
else
  Label1.Text = "Hello, world!";

Normally used to cache files, database query results, etc.

Cache.Insert

Provides find grained control over cache expiration.

Parameters available for function include:

  • key - name used to access cached object
  • value - the data to cache
  • dependencies - a CahceDependencyObject identifies a file or other cache entry. When this changes the entry should be expired.
Cahce.Insert("FileCache", File.ReadAllText("SourceFile.txt"), new CacheDependency(Server.MapPath("SourceFile.txt"));

can create multiple dependencies for single item by adding the CacheDepedcy objects to an AggregateCacheDependency object.

  • absoluteExpiration - time at which the object should expire. Cahce.Insert("FileCache", File.ReadAllText("SourceFile.txt"), null, DateTime.Now.AddMinutes(10));
  • slidingExpiration - period of time which should elapse after last access before expiration. With heavily used objects it is possible that an entry will ever be removed from the cache.
  • priority - determines which items should be removed first in low memory scenarios, ranging from; Low, BelowNormal, Normal, AboveNormal, High, NotRemovable
  • onRemoveCallback - event handler to be called when object is removed from cache

Page Output Caching

ASP supports page output caching, keeping a copy of the rendered page output in memory. If page show dynamic content, or is customised for individual users then don't want this form of caching.

Each page can be configured to be cached independently.

Manage via @ OutputCahce directive at top of page mark-up. Available attributes:

AttributeDescription
DurationNumber of seconds to cache page - required if not using CahceProfile
LocationOutputCacheLocation enumeration value - Any, Client, Downstream, Server, None, ServerAndClient
CacheProfileName of cache settings to associate with page - default ""
NoStoreBoolean determining whether to prevent secondary storage of sensitive information
VaryByParamSemicolon separated list of strings used to vary the output cache. These strings correspond values sent along with Get or Post request. The output cache contains a different version of the requested document for each of the strings. If you don't want to specify a parameter to vary cached content then use the value "none". To vary output cache by all parameter values use value "*". Either this or VarByControl must be provided for all ASP.NET pages featuring user controls. Example: <@OutputCache Duration="15" VaryByParam="search;category" %>
VaryByControlUsed to vary user controls output cache. Must identify the ASP.NET generated name of control, e.g. <@OutputCache Duration="15" VaryByControl="ct100$MainContent$ChoiceDropDownList" %>
SqlDependency    Identifies set of database and table name pairs on which the page / control cache depends. The SqlCacheDependency class monitors these database entries and purges the cache when they change.
VaryByCustomAny text that represents custom caching requirements. If has value of browser, then cache varied by browser name and major version. If custom string provided, then override GetCaryByCustomString in applications Global.asax file.
VaryByHeaderSemicolon separated list of HTTP headers used to vary output.

 

Location, CacheProfile and NoStore attributes cannot be used with user controls.

Shared attribute cannot be used with ASP.NET pages.

To cache page for 900 seconds, regardless of parameters provided:

<@ OutputCache Duration="900" VarsByParam="none" %>

Partial page caching

Move the part of the page you want to cache to a user control and add the @ OutputCache directve to it.

Programmatically Configuring Caching

Can make run-time caching decisions via the Response.Cache object.

  • Response.Cache.SetExpires - expires page at specific time
  • Response.Cache.SetCacheability - used to specify calue from HttpCacheability enum, such as Public (caching at both client and server) or Server (disables client caching)
  • Response.Cache.SetValidUntilExpires - when true cache ignores cache-invalidation headers

Using substitution to update caches

As an alternative to using separate user controls for dynamic elements and configuring different caching policy for these controls, can use one of two cache substitution techniques:

  • Response.WriteSubstitution method - add static place holders to page where dynamic content required. Use Response.WriteSubstitution to specify method that replaces portions of cached page with dynamically generated content. To specify substitution method provide a callback method to WriteSubstitution. Note, can't use with cached user controls where output caching applied at user control level.
  • Substitution control - similar to label controls. Are exempt from caching. There only useful property is Substitution.MethodName which is used to specify method that generates content. Method specified must accept HttpContext and return a string. The string value is inserted in place of the Substitution control.

Determining whether to return cached page prior to rendering

To control whether cached version of page is sued, or page is regenerated code should respond to ValidateCacheOutput event and set valid value to HttpValidationStatus attribute.

  • HttpValidationStatus.Invalid - cause cache to be invalidated so that page is regenerated. Newly generated page stored back in cache.
  • HttpValidationStatus.IgnoreThisRequest - causes current page request to be dynamically generated without invalidating or replacing the previously cached version.
  • HttpValidationStatus.Valid - causes the cached page to be returned.

Then from Page.Load event handler call AddValidationCallback method and pass an HttpCacheValidationHandler object with you method, e.g.

protected void Page_Load(object sender, EventArgs e)
{
  Response.Cache.AddValidationHandler(new HttpCacheValidateHandler(ValidateCacheOutput), null);
}

Creating cache output dependency

To create cache page output dependency call:

  • Response.AddCacheDependency - validity of cache response depends on a CacheDependencyObject
  • Responsr.AddCachItemDependency and Responsr.AddCacheItemDependencies - validity of cached response depends on one or more items in cache
  • Response.AddFileDependency and Response.AddFileDependencies - validity of cached response depends on one or more files

Configuring caching for application

Can configure caching profiles to be referenced from pages within application. Provides centralised configuration of caching. Cretae by adding <caching><outputCacheSettings><outputCacheProfiles> sections to <system.web> of configuration file:

<caching> <outputCacheSettings> <outputCacheProfiles> <add name="OneMin" enabled="true" duration="60" /> </outputCacheProfiles> </outputCacheSettings> </caching>

Caching profiles support most of the same properties as @ OutputCache directive.

Must provide name attribute to identify profile.

Can use enable attribute to disable profile if required.

Reference cache profile within page by using CacheProfile attribute of @ OutputCache directive.

Download