in

ASP.NET Weblogs

The ASPSmith's Blog

Some rants about ASP.NET by Steven Smith

The Caching Pattern

Here's a little something that I term "the caching pattern" for using the ASP.NET cache object:

Object cacheItem = Cache[key]

as DataTable;

if(cacheItem == null)

{

  cacheItem = GetData();

  Cache.Insert(key, cacheItem, null, DateTime.Now.AddHours(1), TimeSpan.Zero);

}

return (DataTable)cacheItem;

 

The as keyword will try to cast Cache[key] to DataTable and if unsuccessful it will return null.  If it is null, it will return null.  The rest of it is pretty straightforward.  This is the best practice way to get something from the cache, but look at it!  It's huge!  I'm trying to come up with a helper class that will encapsulate this logic in a reusable fashion so that reading something from cache would take only a line or two of code.  I'll post more when I'm done - I think I'm close to having it.

[Listening to: Queens of the Stone Age - No One Knows]

 

Comments

 

TrackBack said:

HumanCompiler
June 20, 2003 11:44 PM
 

Jason Gaylord said:

Great example Steve! I noticed the "as" keyword before but never used it. Let me know when the helper class is done. I have a specific use for it.

Thanks,
Jason
June 26, 2003 9:54 AM
 

TrackBack said:

April 2, 2004 12:36 PM
 

TrackBack said:

April 11, 2004 2:56 PM
 

TrackBack said:

April 11, 2004 2:57 PM
 

Gavin Joyce's Blog said:

IntroductionCaching is one of the greatest strategies for improving the performance of our applications....
May 23, 2006 6:42 PM
 

Gavin Joyce's Blog said:

IntroductionCaching is one of the greatest strategies for improving the performance of our applications....
May 23, 2006 6:53 PM
 

Michael Freidgeim said:

I have posted my "Generic LoadFromCache method to reliably read data from cache"

geekswithblogs.net/.../Generic-LoadFromCache-method.aspx

October 8, 2007 7:21 AM
 

Andrew said:

This is great as long as your cache didn't go kafluff on you which is what many developers are falling into. The real pattern that is needed is which caching model is a guaranteed success. Do we have to go with yet another Microsoft Building Block Design Pattern Magical Mystery Tour OR do we expect ASP.Net caching to work out of the box.

March 11, 2008 4:19 PM
 

Alan Northam said:

devlicio.us/.../cold-hard-cache.aspx

Trust but verify pattern.

April 3, 2008 1:08 PM

Leave a Comment

(required)  
(optional)
(required)  
Add