Powered by Blogger.

Thursday, September 26, 2013

Caching in Asp.Net



Caching is a very good technique provided by Asp.Net to improve performance of a Asp.Net site. Caching is the process of storing frequently used data on the server to fulfill subsequent requests. This technique improves web response time. Through this technique we store some static or dynamic content in server cache memory so that web server can easily retrieve data in the next time when the request come. This also minimizes the database hits as well as minimize the consumption of server resources.

There are different types of caching in asp.net like below:

1. Page Level Output Caching:
This is the most simplest form of caching. Output caching simply keeps a copy of the HTML that was sent in response to a request in memory. Subsequent requests are then sent the cached output until the cache expires, resulting in potentially very large performance gains.

To implement page output caching we have to add OutputCache directive to the page like below:

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

Here Duration and VaryByParam are mandatory parameters and appart from that there are also parameters like Location, VaryByHeader, VaryByCustom.

Duration: specifies the time the page should be cached (in seconds).

VaryByParam: Specifies the name of variables for request. The value "none" represents  no variation and the value "*" represents to create new cache entries for every different set of variables.

2. Fragment Caching or User Control Output Caching:
Like page level caching we can also implement caching to the user controls. Fragment caching allows us to cache certain blocks of your website.

To implement caching we have to add OutputCache directive like below:

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

The parameters will be as explained in the Page Level Output Caching.

3. Data Caching:
The above type of caching will be helpful in caching the output of a page. We can also cache DataSet objects like below:

Cache["MyDataSet"] = dsMyDataSet;

Similarly to retrieve the dataset from the cache we can use like below:

DataSet dsFromCache = new DataSet();
dsFromCache = (DataSet)Cache["MyDataSet"];



0 comments

Post a Comment