Friday, October 4, 2013

Implementing Caching in ASP.NET

Caching is a technique of persisting the data in memory for immediate access to requesting program calls. Many in the developer community consider caching as one of the features available to improve performance of Web applications
Methods of Caching
We can deal with caching in several ways. Different caching methods are given below:
  • Output Caching
  • Partial Page Caching
  • Data Caching
Output Caching
Output Caching is a way to keep the dynamically generated page content in the server’s memory to fulfill future requests. You apply output caching by inserting an OutputCache page directive at the top of an .aspx page as shown below.
<%@ OutputCache Duration=”60″ VaryByParam= “None”  %>
The Duration attribute defines the number of seconds a page is stored in memory.

Partial-Page Output Caching
More often than not, it is impractical to cache entire pages. For example, you may have some content on your page that is fairly static, such as a listing of current inventory, but you may have other information, such as the user’s shopping cart, or the current stock price of the company, that you wish to not be cached at all. Since Output Caching caches the HTML of the entire ASP.NET Web page, clearly Output Caching cannot be used for these scenarios: enter Partial-Page Output Caching.
Data Caching
Output Caching is done almost declaratively. But you can perform data caching programmatically. You can use cache object to start caching specific data items for later use on a particular page. The cache object enables you to store everything from simple name/value pairs to more complex objects like datasets and entire aspx pages.
You can use the cache object in the following fashion:
Cache["dataset"] = mydataset;
After an item is in cache, you can retrieve it later as shown below:
DataSet ds = new DataSet();
ds = (DataSet)Cache["dataset"];
Using cache object is an outstanding way to cache your pages. Above fragment shows simple use of the Cache object.

No comments:

Post a Comment