Friday, March 5, 2010

ASP.NET Caching

The ASP.NET 2.0 Framework supports the following types of caching:
  • Page Output Caching
  • Partial Page Caching
  • DataSource Caching
  • Data Caching
    • When using the cache, it is important to understand that items that you add to the cache might not be there when you attempt to retrieve the item in the future. The cache supports scavenging. When memory resources become low, items are automatically evicted from the cache.
    • When you add an item to the Cache, you can specify a particular priority for the item. Specifying a priority provides you with some control over when an item gets evicted from the Cache.
    • You can add almost any object to the cache. For example, you can add custom components, DataSets, DataTables, ArrayLists, and Lists to the cache.
    • You shouldn’t add items to the cache that depend on an external resource. For example, it does not make sense to add a SqlDataReader or a FileStream to the cache. When using a SqlDataReader, you need to copy the contents of the SqlDataReader into a static representation such as an ArrayList or List collection.
    • Adding Items with Dependencies: When you add an item to the Cache object, you can make the item dependent on an external object. If the external object is modified, then the item is automatically dropped from the cache.
    • You can configure the size of the cache by using the web configuration file. Notice that you can’t set the size of the cache directly. However, you can specify limits on the overall memory that your application consumes, which indirectly limits the size of the cache.
Code Sample:




private string GetDataFromCache()


{


var data = context.Cache["data"];


if (data == null)


{


lock (lockString)


{


if (data == null)


{


data = GetData();


context.Cache.Insert("data", data, null, DateTime.Now.AddMinutes(5), System.Web.Caching.Cache.NoSlidingExpiration);


}


}


}


return data.ToString();


}






References:
blog comments powered by Disqus