Thursday, August 25, 2011

ASP.NET Caching Tutorial (with examples)

There are two kinds of caching in

1>Page output caching:  What this does is it stores  the HTML output from the previous request and keeps serving the same output for subsequent requests until the stored cache times out.
Consider the example below, suppose you have a page that presents data from a database. The data it pulls from the database only changes once every few hours. In a case like this if you enable output caching with an expiry of 10  mins, you will hit the database only once in 10 mins.  If there are a large number of users, this will dramatically reduce the load on the database. The only downside to this is, the user could see outdated data for up to 10 mins.

Example: Adding this to the top of your will preserve this page for 600 seconds (10 mins)
<%@ OutputCache Duration="600" VaryByParam="None" %>

2>Application data caching: This is meant for storing data at an application level. It differs from application variables in the sense that application caching is usually meant for large amounts of data that needs to be periodically refreshed.

Example of application caching:

In the example below I will show you how to load a datatable into cache. This cache is set to expire at midnight everynight. Every time the cache gets destroyed due to expiry or underuse, it gets reloaded.

//Declare a variable of the delegate type CacheItemRemovedCallback
CacheItemRemovedCallback cacheRemovedDelg;

//Add the datatable ds.Tables["Vendor"] to cache

“Vendor”,                      //1
ds.Tables["Vendor"],           //2
null,                          //3
DateTime.Today.AddDays(1),     //4
Cache.NoSlidingExpiration,     //5
cacheRemovedDelg               //7

What the numbers above mean is expalined below

1> Key (Name)  assigned to the cache item
2> Data to be added to the cache
3> Anything that the cache depends on
4> This cache will expire at midnight
5> Set to no sliding expiration ( If instead a sliding expiration say for eg 20mins is set,then the the cache will expire after 20 mins after it was loaded )
6> The cache item that will not get removed due to shortage of memory
7> This delegate points to the function to be called when the cache is destroyed for any reason (Will not be called when cache is removed due to an application restart)

If you want to reload the application cache when it gets removed do this

Add this line of code to the Page_Load()  event handler.

cacheRemovedDelg = new CacheItemRemovedCallback(OnCacheRemoved);

Then declare this method on that page

private void OnCacheRemoved(string key, Object value, CacheItemRemovedReason reason)
     if (reason.ToString() == "Expired" || reason.ToString() == "Underused")
         // Reload cache in here

Modify IIS settings

The default app pool worker process is killed after 20 mins of inactivity. With that all the cache variables disappear. So my recommendation is to create your own app pool. Then raise the worker process shut down after an idle time (default 20 mins) and the recycle worker process (default 1740 mins) to  something that works for you . 

Check out this link for more on IIS settings

Further Reading
ASP.NET Caching:

No comments:

Post a Comment

Comments will appear once they have been approved by the moderator