Nitobi
About Nitobi
Services
Products
Home -> Blogs -> Alexei@Nitobi

Alexei@Nitobi

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.

3 Responses to “Ever need to clear your ASP.NET Cache?”

  1. Yoon Says:

    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)

  2. Alexei Says:

    Thanks for pointing that out, Yoon. Good point – we definitely should lock it before doing what we’re doing here.

  3. reck Says:

    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

Leave a Reply


Search Posts

Pages

Archives

Categories

LinkedIn Profile

  • My Profile

www.flickr.com


My ideal work culture:
[See my summary] [What’s yours?]


All contents are (c) Copyright 2024, Nitobi Software Inc. All rights Reserved
Alexei@Nitobi Entries (RSS) and Comments (RSS).