|
What is caching ?
In a very simple term caching is process of storing data in memory,
frequently used data which is very costly to reproduce, is kept in a
memory and re used. One of the ways to improve the throughput is to use caching
in web pages. Caching is a tried and tested technique for performance
improvement. HTML pages have been cached to improve the speed. An indirect
example of caching could be connection pooling.
ASP.Net supports caching the Asp.net response page that is generated by
requests and also storing individual objects in memory.
The cache can be stored on the server or the requesting client or the proxy
server as specified in the settings (discussed below).
Caching ASP.Net pages.
Caching can be achieved in ASP.Net pages by the following 2 ways.
-
Specify the @OutputCache directive at the top of the ASP.Net page
-
Program against the HttpCachePolicy class. This class can be accessed from the
HttpResponse.Cache property of the Page.Response property.
When one of these are added to the ASP.Net page, the response page is saved in
the cache when the first Get method is made for the page. Subsequent GET, POST
and HEAD requests for the page then refer to the cache untill the cache
expires.
Responses generated by the GET request with query strings or the POST request
can be cached with explicit settings. In that case, the GET requests with
identical key-value pairs refer to the cache as long as the duration
is set. Only when the case is changed or with different values or pairs,
a new response is generated (and cached for later use).
Following are some of the key concepts for caching ASP.Net pages.
-
Set the expiration policy.
Using @OutputCache directive. Include this directive at the top of the aspx
page which you want to cache.
<%@ OutputCache Duration="60" VaryByParam="None" %>
Duration is the lifetime of the cache in seconds. We will discuss the
VaryByParam attribute in detail in some time.
Using the Cache class in your code-behind class or in the code for the aspx
page.
Response.Cache.SetExpires(DateTime.Now.AddSeconds(60));
Response.Cache.SetCacheability(HttpCacheability.Public);
-
Set the Location of the Cache.
Using the @OutputCache Directive :
Client Cache :
<%@ OutputCache Duration="60" Location="Client" %>
Proxy Server Cache :
<%@ OutputCache Duration="60" Location="Downstream" %>
Server Cache:
<%@ OutputCache Duration="60" Location="Server" %>
No Cache:
<%@ OutputCache Location="None" %>
Using the Cache Class
Client Cache
Response.Cache.SetExpires(DateTime.Now.AddSeconds(60));
Response.Cache.SetCacheability(HttpCacheability.Private);
Proxy Server Cache
Response.Cache.SetExpires(DateTime.Now.AddSeconds(60));
Response.Cache.SetCacheability(HttpCacheability.Public);
Response.Cache.SetNoServerCaching();
Server Caching
Response.Cache.SetExpires(DateTime.Now.AddSeconds(60));
Response.Cache.SetCacheability(HttpCacheability.Server);
No Cache
Use HttpCacheability.NoCache
-
Caching Multiple Versions of a Page.
-
Caching Based on query string and form POST parameters – specify the attributes
in a semi-colon separated list in ValueByParams in the OutputCache directive.
Each request that arrives with that attribute and a different value will be
cached separately.
<%@ OutputCache Duration="65" VaryByParam="DeptId;EmpId" %>
You can use the wildcard * to specify all values.
The first time the page is requested, the response is generated and added to
the cache. If the page is requested within 65 seconds with the same values for
DeptId and EmpId, then the cached version is used.
-
Caching based on the HTTP header specifies in the ValueByHeader attribute in
the OutputCache directive.
<%@ OutputCache Duration="60" VaryByHeader="Referer" %>
The first time the page is requested, the response is generated and added to
the cache. If the page is requested from the same link within 60 seconds, the
copy from the cache is used.
-
Caching based on a custom function. Include a VaryByCustom attribute and
override the HttpApplication.GetVaryByCustomString in the Global.asax
file.
Include this at the top of the aspx page
<%@ OutputCache Duration="60" VaryByCustom="Frames" %>
Include this in the global.asax page.
public override string GetVaryByCustomString(HttpContext context, string arg)
{
switch (arg)
{
case "Frames":
return "Frames=" + context.Request.Browser.Frames;
case "JavaScript":
return "JavaScript=" + context.Request.Browser.JavaScript;
default:
return "";
}
}
Caching Portions of ASP.Net pages
This is also called fragment caching. Parts of the ASP.Net page which are to be
cached are encapsulated in Web Forms User Controls. Include the @OutputCache
directive at the top of the user control page.
<%@ OutputCache Duration="65" %>
You can add an ID attribute in the user control tag that you have decided to
cache. You should check for the existence of the user control in the output
cache before using it. Any program logic that must occur to create the
control must be included in the user control class itself in events like
Page_Load or Page_Prerender.
-
Cache multiple versions based on values set for properties of the control.
<%@ OutputCache Duration="10" VaryByControl="EmpId;Dept"
VaryByParam="*"%>
-
Cache multiple versions based on values of declarative attributes set in the
user control tags
<MyUC:List Dept="HR" runat="server" />
Caching Application Requests.
You can add expensive objects or frequently used objects to the cache. The
objects are stored in name-value pairs similar to dictionary in the
cache.
Add an item to the cache
-
By specifying the key value:
Cache["Asset"] = txtAsset.value;
-
By using the Insert method
Cache.Insert("Asset", oString);
-
By using the Add method
Cache.Add("Asset", oString);
You can specify an expiration date in terms of absolute time interval or in
terms of interval of time since the last access.
Absolute Expiration of 1 minute:
Cache.Insert("Asset", oString, null, DateTime.Now.AddMinutes(1),
NoSlidingExpiration);
Sliding Expiration of 1 minute from the last access time:
Cache.Insert("Asset", oString, null, NoAbsoluteExpiration,
TimeSpan.FromSeconds(60));
You can specify validation based on another file, directory or another cached
item. This is called file dependency or key dependency.
Cache.Insert("Asset", oString, new
CacheDependency(Server.MapPath(\\Server\myDependency.xml)));
When the myDependency.xml file changes, the cached copy of oString is
removed.
You can specify the priority of the cache item using the CacheItemPriority
enumeration values or the CacheItemPriorityDecay enumeration values. When the
system resources like memory are low, the server deletes of the least used or
unimportant items from the cache. This is called scavenging. The items to be
deleted are decided based on the priority set for the item.
Retrieve an item from the cache
. . .
Source = (DataView)Cache["MyData1"];
if(Source != null ) {
. . .
}
Note that we have to check for the existence of the cached item before
using it.
Delete Items from Cache
Items are deleted from cache when the expiration is set or when the dependency
file changes or when the server needs to free memory.
Cache.Remove("oString");
Notify an Application when an item is removed from the cache.
The CacheItemRemovedCallback delegate in the .Net framework defines the
signature to use when you want to write event handlers to respond when an item
is deleted from cache. Typically, the event handler would include code to add
the item in cache again.
-
Create the local variable that raises the event for the
CacheItemRemovedCallBack delegate.
private static CacheItemRemovedCallback onRemove = null;
-
Create an event handler to respond when the item is removed from cache.
public void onRemoveCallBack(string str1, object obj1, CacheItemRemovedReason
r)
{
. . .
DataSet ds = GetEmpInfo
Cache["empDS"] = ds;
. . .
}
-
Create an instance of the CachedItemRemovedCallBack delegate that calls the
event handler
onRemove = new CacheItemRemovedCallback(this. onRemoveCallBack);
-
Add the item to cache using the Add or Insert method.
Cache.Insert("empDS", ds, null, DateTime.Now.AddMinutes(1),
NoSlidingExpiration, CacheItemPriority.High,
CacheItemPriorityDecay.Slow, onRemove);
|