In this blog I'll explain the Asp.net caching overview and how to use caching in your asp.net projects. So lets start with few basic things:--
1) What is caching?
Caching is a technique of storing frequently used data in memory, so that, when the same data is needed next time, it could be directly retrieved from the memory instead of hit the database everytime.Caching is extremely important for performance boosting in ASP.NET.
2)Advantages of Caching ?
- It increases performance of the application.
- It decreases server round trips for fetching data from database by persisting data in the memory.
- It greatly reduces overhead from server resources.
3) Types of Caching ?
There are three types of caching available in asp.net.
- Output Caching
- Fragment Caching
- Data Caching
Output Caching :--
Out put caching is at the page level and one of the easiest way for caching pages. To implement the Output Caching on your page you need to add the @ OutputCache directive to page.
It includes the following attributes.
- Duration
- VaryByParam
Syntax: <%@ OutputCache Duration="60" VaryByParam="none" %>
In the above Syntax, we have specified VaryByParam="none".By not giving the value to the attribute VaryByParam="none", then for the specified time period like Duration="60" the user can see the same value given with the 60 seconds.So this is stale data which we are seeing. So if we want to see the cache based data, then we can specify the VaryByParam's value.
Fragment Caching :--
The Fragment caching allows to cache specific portions of the page rather than the whole page. Like an user controls within a Web Form. Fragment caching comes from the attribute "VaryByControl". Using this attribute we can cache a user control based on the properties exposed.
Syntax: <%@ OutputCache Duration="60" VaryByControl="MyUserControl" %>
Application Caching :--
Application caching is a mechanism for storing the Data objects on cache.
Example:--- In below example we are try to save the date time object in Application cache.
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack == false)
{
Cache["TodaysDayTime"] = DateTime.Now;
}
LabelApplication.Text = ((DateTime)Cache["TodaysDayTime"]).ToLongTimeString();
}
1 Comment(s)