When going through the asp.net forums, one thing I've noticed is that there
is a lack of understanding among many devs about ASP .Net caching. The majority
of the problems are caused when trying to use the Cache as a reliable
in-memory storage medium. The Cache object is not meant to do this.
Cache storage is volatile, It can be garbage collected, it can expire, and it
is not expected to be synched in a web farm.
So far I've used the Cache to avoid expensive db hits. I use a
refactoring approach to storing data in the Cache.
First I write my usual data access and data binding code with,
Datatable userDataTable;
userDataTable = DataUtils.GetUsers();
//bind and display
Now to cache the user date, I refactor the code to this,
DataTable userDataTable;
userData = Cache["USER_DATA"];
if(userData == null){
userDataTable = DataUtils.GetUsers();
//code to refresh cache, insert etc...
Cache.Insert("USER_DATA",userDataTable);
}
//bind and display
This simple practice ensures
that there is always data, and handles a cache miss gracefully. Any thoughts on
this ?