Welcome to AspAdvice Sign in | Join | Help

Extending the ASP.NET Cache Object: Cache.Clear()

The built-in Cache object in ASP.NET does not support a Clear() method.  This method would be useful if you ever just wanted to invalidate all cache entries and start fresh.  In a utility object I'm working on, tentatively called SuperCache, I've implemented a Clear method using the following code:

  /// <summary>
  /// Removes all items from the Cache
        /// Note - should not remove from cache in while loop since enumerator is only valid while collection remaind intact:
        ///
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpref/html/frlrfsystemcollectionsidictionaryenumeratorclasstopic.asp
  /// </summary>
  public void Clear()
  {
            List<string> keyList = new List<string>();
   IDictionaryEnumerator CacheEnum = _cache.GetEnumerator();
            while (CacheEnum.MoveNext())
            {
                keyList.Add(CacheEnum.Key.ToString());
            }
            foreach (string key in keyList)
            {
                Remove(key);
            }
  }

This is interesting mainly because of the reference to the IDictionaryEnumerator documentation, which states

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 the next call to MoveNext or Reset throws an InvalidOperationException. If the collection is modified between MoveNext and Current, Current will return the element that it is set to, even if the enumerator is already invalidated.

Since my original code, borrowed from others who will remain nameless, called Remove() inside the while loop, I thought I'd post this since I'm sure others are probably making the same mistake.  I never encountered any errors and I have a bunch of unit tests that all pass using my old way of doing things, but I figure it's probably safest to go with what the docs say and do the removal after I'm finished with the enumerator.

Published Monday, November 14, 2005 4:25 PM by ssmith
Filed under: , , ,

Comment Notification

If you would like to receive an email when updates are made to this post, please register here

Subscribe to this post's comments using RSS

Comments

# re: Extending the ASP.NET Cache Object: Cache.Clear()

I'm surprised you never got any errors with your old code that removed items within the while loop. I've done the same thing a couple of times before learning my lesson, and it always generated an exception.
Monday, November 14, 2005 5:20 PM by David Neal

# re: Extending the ASP.NET Cache Object: Cache.Clear()

Great suggestion Steve. I guess you'd want to implement an error handler though in case you are trying to clear the cache and the value does get changed.
Tuesday, November 15, 2005 9:06 AM by Jason N. Gaylord

# re: Extending the A'SP.NET Cache Object: Cache.Clear()

ASP.NET Cache Object: Cache.Clear()

Great suggestion Steve. I guess you'd want to implement a'n error handler though in case you are trying to clear the cache and the value does get changed.

Tuesday, November 15, 2005 9:06 AM by Jason N. Gaylord '''

never got any errors with your old code that removed items within the while loop. I've done the same thing a couple of times before learning my lesson, and it always generated an exception.

Monday, November 14, 2005 5:20 PM by David Neal

Wednesday, November 15, 2006 2:14 AM by Cache.Cl'ealear

# re: Extending the ASP.NET Cache Object: Cache.Clear()

In VB:

For Each elem As DictionaryEntry In Cache

   Cache.Remove(elem.Key)

Next

When you iterate on the public cache, you really work on a copy of the data—a hashtable—that is obtained locking the Cache and enumerating its contents. For this reason, there’s no need to lock the cache for the preceding loop. And there’s no guarantee either that the cache is really empty when you’re done. The underlying Cache isn’t really locked and concurrent requests can modify it. This is by design and to privilege in terms of performance the most common uses of the Cache object.

(taken from msd2d.com)

Tuesday, July 24, 2007 9:03 AM by D Osborn

Leave a Comment

(required) 
required 
(required) 
Enter the code you see below