Caching in ASP.NET
page 1 of 1
Published: 24 Mar 2006
Unedited - Community Contributed
Abstract
Caching can dramatically improve the performance of your application by storing the page output or application data across HTTP requests. In this article, Joydip discusses the different types of Caching in ASP.NET with lucid code examples.
by Joydip Kanjilal
Feedback
Average Rating: This article has not yet been rated.
Views (Total / Last 10 Days): 55907/ 64

Caching is a feature of ASP.NET that improves the performance of web applications by minimizing the usage of server resources to a great extent. This article discusses Caching, its types and contains some lucid code examples to illustrate On- Demand Data Caching.

What is Caching?

Caching is a feature that stores data in local memory, allowing incoming requests to be served from memory directly.

Benefits of Caching

The following are the benefits of using Caching

·         Faster page rendering

·         Minimization of database hits

·         Minimization of the consumption of server resources

Types of Caching

Caching in ASP.NET can be of the following types

·         Page Output Caching

·         Page Fragment Caching

·         Data Caching

Page Output Caching

This is a concept by virtue of which the output of pages is cached using an Output Cache engine and all subsequent requests are served from the cache. Whenever a new request comes, this engine would check if there is a corresponding cache entry for this page. If there is a cache hit, i.e., if the engine finds a corresponding cache entry for this page, the page is rendered from the cache, else, the page being requested is rendered dynamically.

This is particularly useful for pages that are static and thus do not change for a considerable period of time.

Page output caching can be implemented in either of the following two ways:

·         At design time using the OutputCache directive

·         At runtime using the HttpPolicy class

The following is the complete syntax of page output caching directive

<%@ OutputCache Duration="no of seconds"
Location="Any | Client | Downstream | Server | None"
VaryByControl="control" 
VaryByCustom="browser |customstring"
VaryByHeader="headers"
VaryByParam="parameter" %>

The following statement is used to implement output caching in an aspx page at design time.  The directive is placed at the top of the .aspx page.

<%@OutputCache Duration="30"
VaryByParam="none" %>

The duration parameter specifies for how long the page would be in cache and the VaryByParam parameter is used to cache different views of the page. In the code example above, the cache duration is 30 seconds. Cache duration is a required field, and must be set to an integer greater than zero.  The VaryByParam parameter, which is also required, specifies whether the cached page would differ in versions based on any parameter. A value of * in the same parameter indicates that the page would be cached based on all the Get/Post parameters. We can also specify one or more Get/Post parameter(s). Hence, the same statement shown above can have the following variations. The VaryByParam parameter is particularly useful in situations where we require caching a page based on certain criteria. As an example, we might require to cache a specific page based on the EmployeeID.

<%@OutputCache Duration="30"
VaryByParam="*" Location = "Any"%>   
<%@OutputCache Duration="30"
VaryByParam="EmployeeID" Location = "Client" %>   
<%@OutputCache Duration="30"
VaryByParam="EmployeeID;Basic" %> 

The VaryByParam parameter can also have multiple parameters as shown in the example above.

The location parameter is used to specify the cache location, either the server of the client.

To set a page's cacheability programmatically we have to use the method Response.Cache.SetCacheability. This method accepts the following parameters

·         NoCache

·         Private

·         Public

·         Server

The code snippet below shows how to set a page’s cacheability programmatically:

Response.Cache.SetCacheability(HttpCacheability.Server);

Additionally we can set other properties which map to the same fields available when using the OutputCache directive on the page:

Response.Cache.SetExpires(DateTime.Now.AddSeconds(30));
Response.Cache.SetValidUntilExpires(true);
Response.Cache.VaryByParams["EmployeeID"]= true; 

 

Page Fragment Caching

This allows specific portions of the page to be cached rather than caching the whole page. This is useful in situations where we can have a page that contains both static and dynamic content. The following code depicts how this can be accomplished.

<%@ OutputCache Duration="15"
VaryByControl="EmpID;DeptID" VaryByParam="*"%>   

This directive is placed at the top of any User Control (.axcx file).

 

Data Caching

The following code is an implementation of On-Demand caching. The method GetUserInfo checks to see if the data exists in the cache. If it is present, it is returned from the cache, else, the GetUserInfoFromDatabase method fills the DataSet from the database and then populates the Cache.

public DataSet GetUserInfo() 
{   
  string cacheKey = "UserInfo";   
  DataSet ds = Cache[cacheKey] as DataSet;   
  if (ds == null)   
 {     
   ds = GetUserInfoFromDatabase();     
   Cache.Insert(cacheKey, ds, null, NoAbsoluteExpiration,       
   TimeSpan.FromHours(15),CacheItemPriority.High, null);   
}      
return ds; 
}   

DataSet GetUserInfoFromDatabase() { 
// Usual code to populate a data set from thedatabase. This data set 
// object is then returned. 
}

Cache Expirations

Cache expirations can be of the following types

·         Time Based Expiration

·         Dependency Based Expiration

Time Based Expiration

This is used to specify a specific period of time for which the page would remain in the cache. The following statement specifies such expiration for a page in the code behind of a file using C#.

Response.Cache.SetExpires(DateTime.Now.AddSeconds(120));

This can also be accomplished by stating the same in the output cache directive as shown here.

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

Cache Expiration

Cache expiration strategies can be implemented in either of the following two ways:

·         Time Based

·         File Based

·         Key Based

Time Based Expiration

This is implemented by specifying a specific duration for which the item would remain in the cache. When the time elapses, the item is removed from the cache and subsequent requests to retrieve the item returns a null. Time based expiration strategies can be of the following two types:

·         Absolute

·         Sliding

Absolute

Cache.Insert("UserInfo", dsUserInfo, null,
DateTime.Now.AddMinutes(1), NoSlidingExpiration); 

Sliding

Cache.Insert("UserInfo", dsUserInfo, null,
NoAbsoluteExpiration, 
TimeSpan.FromSeconds(60));

Note that you cannot use both Absolute and Sliding expirations at the same time.

File Based Expiration

This is implemented by using a file as a dependency. Whenever the contents of the dependency file are changed, the cached is invalidated. Please refer to the code below.

CacheDependency cacheDependency = newCacheDependency("userinfo.xml");
Cache.Insert("UserInfo", xmldocObject,cacheDependency); 

In addition to files, entire folders can be monitored for changes using the CacheDependency class.

Key Based Expiration

The third type of dependency is the key dependency.  With it, a cache entry can be made to depend on another, existing dependency.  When the depended-upon entry changes or expires, the dependent entry will also be expired.  An array of keys can be specified as a single CacheDependency.

string[] keys = new string[] {"key"};
CacheDependency cacheDependency = newCacheDependency(null,keys);
Cache.Insert("UserInfo", xmldocObject,cacheDependency);

 

Using Callbacks

The delegate CacheItemRemovedCallback event handler is used to respond to the event that is raised when an item is deleted from cache. This handler contains the code to populate / re-populate the cache. Please refer to the code snippet below.

public void onRemoveCallBack(string str, objectobj, CacheItemRemovedReason reason) 
{   
   DataSet dataset = GetUserInfoFromDatabase();   
   Cache["userInfo"= dataset; 
} 

1.      First declare a class variable onRemove as shown below.

private static CacheItemRemovedCallback onRemove = null

2.      This delegate is invoked as shown below.

onRemove = newCacheItemRemovedCallback(this.onRemoveCallBack);

3.      The following code snippet shows how this handler is specified when items are added to the Cache.

 
Cache.Insert("userInfo", ds, null, DateTime.Now.AddMinutes(2), 
NoSlidingExpiration, CacheItemPriority.High,
CacheItemPriorityDecay.Slow, onRemove);

The Cache Class

The Add/Insert method of the Cache class is used to add/insert an item into the cache. The Remove method removes a specified item from the cache. The Cache class contains the following properties and methods.

Properties

·         Count

·         Item

Methods

·         Add

·         Equals

·         Get

·         GetEnumerator

·         GetHashCode

·         GetType

·         Insert

·         Remove (Overloaded)

·         ToString

Conclusion

Judicious use of the right type of caching can dramatically improve the performance of web applications.  For more information about caching, please visit the ASPAlliance Caching Reference.



User Comments

Title: suggestion   
Name: santosh dubbewar
Date: 11/2/2006 3:37:03 AM
Comment:
really its nice article but its better to mention all these 3 types with one webpage.(practical approach)
Title: Suggestion   
Name: freeman
Date: 8/2/2006 7:32:02 PM
Comment:
It is a wonderful article and I learned a lot from it but if you can create a small web page where you can apply the three type of caching to get the real flavour of them.
Title: Mr   
Name: Harish
Date: 7/14/2006 12:05:34 PM
Comment:
Good Arcticle ....
Title: Shri   
Name: Hemendra
Date: 6/20/2006 3:31:10 AM
Comment:
hii all
pretty good material to work on caching
Title: caching   
Name: jagadish
Date: 6/18/2006 7:26:41 AM
Comment:
superb
Title: Mr   
Name: inam ullah
Date: 4/12/2006 2:50:49 AM
Comment:
i have learned a lot from this article.now i have no dificulty to use cashe
inam from pakistan
Title: A   
Name: ASP.NET Developer
Date: 4/6/2006 4:15:48 AM
Comment:
My new site has many pages which could benefit from caching since they only potentially change when I occasionally update the database. I'm going to try this out - and add a link to this nice article too. I've got a number of links to articles/tutorials on this site now. Thanks!
Title: My Opinion   
Name: Venkatesa Prasath Varatharajan
Date: 4/5/2006 1:18:31 PM
Comment:
Very Nice Article.I learned lots from this.Keep it up.

Thanks & All The Best
Title: Mr.   
Name: Jayaraman
Date: 4/5/2006 5:37:16 AM
Comment:
In this article a line has mensioned like this "
The location parameter is used to specify the cache location, either the server of the client".

I am in doubtfulness whether it is correct or not

Product Spotlight
Product Spotlight 





Community Advice: ASP | SQL | XML | Regular Expressions | Windows


©Copyright 1998-2014 ASPAlliance.com  |  Page Processed at 11/21/2014 6:56:11 PM  AspAlliance Recent Articles RSS Feed
About ASPAlliance | Newsgroups | Advertise | Authors | Email Lists | Feedback | Link To Us | Privacy | Search