Techbubbles

Using Caching in ASP.NET Web Applications

Caching is a way which you can use to improve the performance of an ASP.NET Web applications. Caching is a location where you can store the data and access quickly. You have to use caching carefully and this post explains different caching mechanisms that available in ASP.NET web applications.The three ways that you can use to store the Cache data in ASP.NET applications are

Output Caching

Caching API

Using Cache in Data Source Controls

Output Caching

Output Caching allows you render the cached web page. When you request the web page very first time, the response will be added to the cache. Subsequent requests now onwards to the same page will be served from the cache. When you send the request second time, it actually would not process your code at server, it just returns the same HTML in the cache to the user. Enabling output cache is simple, add a OutputCache directive to your page directive as below

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

The Duration is in seconds which tells the frequency that you want to cache the page before ASP.NET creates a new copy. This solution is ideal for static web pages where the content would not change very frequently. You can use VaryByParam for dynamic pages where the content changes by query string value. for example if your request page url looks as below

http://localhost:40967/Products/ViewDetails.aspx?Id=123

It caches the product id 123 details but when you pass another product id in query string then it fails to show that details as it is not in the cache. To overcome this issue, ASP.NET allows you to cache the specific version of the page. You can do this by setting VarByParam attribute in OutputCache.

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

You can not use OutputCaching when you have a user specific scenarios like theme personalisation, example when the page is requested and cached for first time logged in user theme will be placed in cache subsequent users when they sent request very first time they will see the theme that in the original request. Avoid using the OutputCaching when you want to show the user specific content on your page.

Caching API

Using the built-in Caching API, you can store and access the  items in cache through C# code. You can use Add or Insert methods to store items in Cache. The difference is Add method returns an object that represents the cached item where Insert method does not. If you add an item to Cache which is already present in cached it then fails where as in Insert method it replaces the existing item. The Add method can be used as below

 Cache.Add("DbConn", ConnectionString, new CacheDependency(filename),
    System.Web.Caching.Cache.NoAbsoluteExpiration,
    System.Web.Caching.Cache.NoSlidingExpiration, 
    System.Web.Caching.CacheItemPriority.Default,null);

You can define the CacheDependency item which can be used invalidate a cached item when the original source is changed. As soon as you changed the CacheDependency file, ASP.NET removes the item from the cache and puts it back by reading the original source file. The Cache Insert method looks as below

   Cache.Insert("DbConn", ConnectionString, new CacheDependency(filename));

You can set the time based expiration on Cached items using two ways

AbsoluteExpiration:Whether you use the cached item or not it will expire after specified amount of time. The data in the cached will expire whether you use the item or not. Use this expiration policy when there is a chance of less change in the cached data.

Cache.Add("DbConn", ConnectionString, new CacheDependency(filename),
    DateTime.Now.AddMinutes(1),
    System.Web.Caching.Cache.NoSlidingExpiration, 
    System.Web.Caching.CacheItemPriority.Default,null);

SlidingExpiration: In this expiration policy it expires the cached item after specific time if any request is not made during the specified time. Use this expiration policy when there is a chance of more change in the cached data.

Cache.Add("DbConn", ConnectionString, new CacheDependency(filename),
    System.Web.Caching.Cache.NoAbsoluteExpiration,
    TimeSpan.FromMinutes(1), 
    System.Web.Caching.CacheItemPriority.Default,null);

You can also notify the application when a particular item being removed from the Cache as shown below

Cache.Insert(
            "DbConn",
            ConnectionString,
            null,
            Cache.NoAbsoluteExpiration,
            new TimeSpan(0, 0, 15),
            CacheItemPriority.Default,
            new CacheItemRemovedCallback(ReportRemovedCallback));
   public static void ReportRemovedCallback(String key, object value,
    CacheItemRemovedReason removedReason)
        {
            // Write the logic here
        }

Using Caching in Data Source Controls

Caching is supported by all data source controls except SiteMap, LinqDataSource and EntityDataSource Controls. Data Source controls only cache database driven data. It would not cached the entire page. You can enable the caching for data source controls using EnableCaching attribute as shown below

<asp:SqlDataSource ID="SqlDataSource1" runat="server" CacheDuration="800"
     EnableCaching="True"> </asp:SqlDataSource>

Note: Items will be removed from the cache itself when Web Application or Web Server restarts.

Related Posts:

%d bloggers like this: