Jun302008

Use Cache[] not Application[]

When i was checking one of my colleague code, i saw that he is using Application[] to hold some values. This is ok, you might be in need of this; however my friend was using this to cache the datatable that returns from the sql server. I asked him, "Why dont use Cache?", guess what he said: "This is my cache, what are you talking about!!". I think he wasnt aware of Cache class in asp.net. I explained him a little bit of the details, and he changed his code. You can use HttpContext.Current.Cache to cache some data, and retrieve them very easily. Not only the ease of usability, but there is also some extra features like dependencies, cache life time etc. For example, you can bind this cache to a sql server table, and the cache mechanism will invalidate the cache when the table changes. Besides putting sql server cache dependency, you can also have cache lifetime, which will invalidate the cache after the time you specified.

An example of caching the datatable is below:

[code:c#]

DataTable dtUsers = new DataTable();  
if (HttpContext.Current.Cache["PhoneBook"] == null)  
{   
     ... get the dtUser from the database    
     HttpContent.Current.Cache.Add("PhoneBook",dtUsers,null,DateTime.Now.AddHours(1),
        TimeSpan.FromMinutes(5),System.Web.Caching.CacheItemPriority.Normal,null);  
}  
else    
    dtUsers = (DataTable)Cache["PhoneBook"];

[/code] 

In the above code, i didnt put any sql server dependency, however i put a cache life time 1 hours,also sliding of 5 minutes.

Why didnt i use Web.Cache? For some reason, System.Web.Cache seems to be working per user, i dont know why?, but when i used HttpContext.Current.Cache everything seems to be working fine. 



Tags: ,

E-mail | Permalink | Trackback | Post RSSRSS comment feed 0 Responses