Ever need to clear your ASP.NET Cache? 
June 7th, 2008
It’s odd there is no global Clear() method on the HttpContext cache. Anyway, this is how you do it:
private static void DeleteAllCacheItems()
{
HttpContext ctx = HttpContext.Current;
IDictionaryEnumerator d = ctx.Cache.GetEnumerator();
while(d.MoveNext())
{
ctx.Cache.Remove(d.Key.ToString());
}
}
|
Del.icio.us
This entry was posted on Saturday, June 7th, 2008 at 2:42 pm and is filed under .net, web development. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

June 19th, 2008 at 7:47 pm
There doesn’t seem to be a thread-safe way to clear the HttpContext cache.
According to the docs for IDictionaryEnumerator:
”
An enumerator remains valid as long as the collection remains unchanged. If changes are made to the collection, such as adding, modifying, or deleting elements, the enumerator is irrecoverably invalidated and its behavior is undefined.
The enumerator does not have exclusive access to the collection; therefore, enumerating through a collection is intrinsically not a thread-safe procedure. To guarantee thread safety during enumeration, you can lock the collection during the entire enumeration. To allow the collection to be accessed by multiple threads for reading and writing, you must implement your own synchronization.
”
People have pointed out to use cache-dependencies or expirations when inserting objects into the cache, but there are times when that is not possible, for example, we are using a 3rd party module that inserts things in the HttpContext without any dependencies and no methods are exposed by that module to clear the items that they put in the cache. (In this case the underlying fault is with the 3rd party module but it would have been nice to have been able to write a workaround for it in our own code by simply calling a thread-safe clear method)
June 21st, 2008 at 3:23 pm
Thanks for pointing that out, Yoon. Good point – we definitely should lock it before doing what we’re doing here.
September 7th, 2008 at 1:19 am
Sometimes cache creates problem. YOu have to handle cache for Correct execution in asp.net
Visit http://developmentzone.blogspot.com/2008/09/prevent-browser-from-caching-webpage.html