Caching in ASP.NET (Part II)

Data Caching using the Cache API   Data Caching is a feature that enables us to store frequently used data in the Cache. The Cache API was introduced in ASP.NET 1.x and was quite exhaustive and powerful. However, it did not allow you to invalidate an item in the Cache based on a change of data in a Sql Server database table. With ASP.NET 2.0, the Cache API provides you a database triggered Cache invalidation technique that enables you to invalidate the data in the Cache based on any change of data in the Sql Server database table. Besides this, you can also create custom cache dependencies. The Cache class contains a numerous properties and methods. Of these, the Add, Insert, Remove methods and the Count property are the most frequently used. The Add/Insert method of the Cache class is used to add/insert an item into the cache. The Remove method removes a specified item from the cache. The Count property returns the current number of objects in the Cache. The Cache property of the Page.HttpContext class can be used to store and retrieve data in the cache. The following code snippet illustrates the simplest way of storage and retrieval of data to and from the cache using the Cache class. //Storing data Cache [“key”] = objValue; //Retrieving the data object  obj = Cache [“key”]; We can also check for the existence of the data in the cache prior to retrieving the same. This is shown in the code snippet below: object obj = null; if(Cache[“key”] != null) obj = Cache[“key”]; The following code snippet illustrates how we can make use of the Cache API to store and retrieve data from the Cache. The method GetCountryList checks to see if the data (list of countries) exists in the cache. If so, it is retrieved from the cache; else, the GetCountryListFromDatabase method fills the DataSet from the database and then populates the Cache. public DataSet GetCountryList() { string key = “Country”; DataSet ds = Cache[key] as DataSet; if (ds == null) { ds = GetCountryListFromDatabase (); Cache.Insert(cacheKey, ds, null, NoAbsoluteExpiration, TimeSpan.FromHours(5),CacheItemPriority.High, null); } else { return ds; } } //End of method GetCountryList public DataSet GetCountryListFromDatabase () { // Necessary code to retrieve the list of countries from the database and // store the same in a DataSet instance, which in turn is returned to the // GetCountryList method. }


Leave a comment

Your email address will not be published.