Lovely Cache Love-in
One of the biggest draws of ASP.NET to me is its great caching abilities. You can send any object to the cache, set its expiration period, and recall with just a few lines of code.
For a quick recap, this is how you use the Cache object:
To put an object into the cache, let’s say the contents of a Label:
Cache[“mylabeltext”] = Label1.Text;
To later recall the cached value:
if (Cache[“mylabeltext”] != null)
Label1.Text = (string)Cache[“mylabeltext”];
Now, thats good stuff!
But one thing escapes me, and I’m not sure really why the functionality seems not to exist. How to iterate the Cache object?
Take the following scenario. I cache search results. When a user enters a search, I first check to see if a cached version of the results is available:
if (Cache[“search”+searchQuery] != null)
// output cache
But say I alter information that affects the search results? Like change the title of an entity…how do I clear the cache of search results that reference this entity? If I could iterate the cache, I could do a quick search through looking for references, and either update the cache or remove them. However, no iterator exists.
One way I devised, which is very messy and ultimately slow, is to have a list of search queries and all the entities they reference. I can then serialize this (or dump it to the cache, as if the cache is deleted, so will all the cached searches!), and quickly pinpoint any cached searches I need to modify.
I just can’t see why an iterator wasn’t implemented on the Cache. Maybe I’m missing something obvious…
Any ideas, dear Sitepointers? :)
DHTMLgod found the GetNumerator in the Cache object:
Dim objCacheItems As Collections.IDictionaryEnumerator
objCacheItems = Cache.GetEnumerator
Good work fella! I’m sure AutoComplete was hiding that… :)
A friend of mine showed me some of his source code to a cache layer he was writing in C#…to me, he was caching at the wrong level, and let me explain briefly what I mean.
He’d cache the results from the database, a DataSet, then process the information to present it on the page. So:
Request -> Cache Layer -> Presentation Layer -> Response
Thing is, it’s much quicker to simply cache at the Presentation Layer…after all, its this output you want to save. Of course, if you need to store a structure which is used to build the presentation, and which is likely to change, then you can cache both the structure and the presentation. So instead of the situation before, caching a DataSet, instead the Cache Layer would return a string or StringArray etc. with the actual content to display, meaning the presentation layer can be bypassed:
Request -> Cache Layer -> Response
It might seem obvious to some, but such design flaws are easily made.