Karine Bosch’s Blog

On SharePoint

Part 6: ASP.NET Caching


You can also write your own caching mechanism to store your business objects by using System.Web.Caching.Cache class. The objects are stored in a dictionary in key/value pairs. You can retrieve your object using the key name.

You can access the cache using different methods like Page.Cache, Context.Cache, HttpRuntime.Cache, Response.Cache.

The expiration of the objects in the ASP.NET cache can be set to automatically or explicitly when needed.

The ASP.NET cache object is unique to each server in the farm and is not shared between servers. Therefore it is possible to have a completely different version of the object on each web front-end.

Following code snippet demonstrates how to work with the ASP.NET cache:

string cacheKey = "BeersOfTheWeek";
List<Beer> beerList = null;
// check the cache
object o = HttpRuntime.Cache.Get(cacheKey);
if (o == null)
{
   object lockHandle = new object();
   lock (lockHandle)
   {
      // check again if cache is not filled again
      o = HttpRuntime.Cache.Get(cacheKey);
      if (o == null)
      {
         beerList = RetrieveWithQuery();
         if (beerList != null)
         {
            // add the list to the cache
            HttpRuntime.Cache.Insert(cacheKey, beerList, null,
                 DateTime.Now.AddMinutes(15.0), TimeSpan.Zero);
         }
      }
      else
         beerList = (List<Beer>)o;
   }
}
else
   beerList = (List<Beer>)o;

First you have to test on the existence of your object in the cache using a well-defined cache key. If your object is found in the cache, it can be casted to the correct type. If not found, it needs to be retrieved from the database. It is a good coding practice to place a lock before retrieving the data. After it has been retrieved, it can be added to the cache using the cache key. You can specify for how long your objects need to be retained in the cache.

You can add an item to the cache using the Add or Insert methods. If you use a DateTime value, you implement absolute expiration meaning that your objects expire after a certain amount of time. Alternatively, you can specify a sliding expiration using a TimeSpan value. This allows you to specify how much time must elapse before the item expires based on the time it was last accessed.

Once an item expires, it is removed from the cache, and only added again when it is requested again.

1 Comment »

  1. Thanks Karine. If cache objects are unique to web servers, how can it be synchronized between the front end servers?

    Comment by PR | June 14, 2016 | Reply


Leave a comment