Skip navigation

Use Caching effectively!

Caching is one of the best techniques you can use in ASP.Net applications. You can cache your user's authentication credentials to complete business object of size that may go to 2-3 MBs.
Simple caching could be below

MyCacheValue = Cache("SomeValue")
If MyCacheValue <> Null Then
    DisplayData(MyCacheValue )
End If

If we have huge database request of thousands of rows, and is frequently viewed and updated, this is the best place to use caching in the second scenario. One has to update both the database and the cache object whenever changes happen. In this way, for viewing we can use only cached object.
This is how we have to go about doing this. First create a new ASPX page and give it a convenient name, say AppCache.aspx and in the code behind page, add these modifications.

using System;
...
using System.Web.Caching;
namespace MyWebApp
{
 /// <summary>
 /// Summary description for WebCache.
 /// </summary>
 public class AppCache : System.Web.UI.Page
 {
   public AppCache()
  {
   Page.Init += new System.EventHandler(Page_Init);
  }

  ...

  private void Page_Load(object sender, System.EventArgs e)
  {
  }
  // Create a function to get/set the cached object.  
  public DataSet getCachedDataSet()
  {
   DataSet piObjDataSet;
   string bizObj = "MyDataSet";
   int CountCache = Cache.Count;
   if(Cache.Get(busObj) == null)
   {
    //Connect to database and get the dataset into piDataset
    ...
    //Insert data into cache
    Cache.Insert(bizObj ,piDataset,null,System.Web.Caching.Cache.NoAbsoluteExpiration,System.Web.Caching.Cache.NoSlidingExpiration,CacheItemPriority.Low,null);
   }
   else
   {
    piObjDataSet = (DataSet)Cache.Get(bizObj);
   }
   return piObjBusiness;
  }
 }
}

Next, all the subsequent pages that need to use this cached object should inherit from this page as shown below.

namespace MyWebApp
{
 /// <summary>
 /// Summary description for MySecondPage.
 /// </summary>
 public class MySecondPage: AppCache
 {
   ...
 }
}

Here we can use the function we declared above to get the required dataset from cache.

Use this technique to its best, avoid more hits to the database.

Hide comments

Comments

  • Allowed HTML tags: <em> <strong> <blockquote> <br> <p>

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.
Publish