Write for Us
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 dataCache ["key"] = objValue;//Retrieving the dataobject 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.}