Main FAQ Category: Beginner (39)
How to clear your ASP.NET applications Cache?
Posted: 30-Mar-2008
Updated: 30-Mar-2008
Views: 76869


ASP.NET comes with very powerful caching mechanism that can be used to easily improve responsiveness and efficiency of your web applications.

You can use Page Caching, Data Caching, and it all works as it should out of the box if you configure it correctly.

One thing that Caching in ASP.NET lacks is the simple way of clearing all items in current Cache.

Here is the code snippet that clears all cached data in your web application:

    public void ClearApplicationCache()

    {

        List<string> keys = new List<string>();

 

        // retrieve application Cache enumerator

        IDictionaryEnumerator enumerator = Cache.GetEnumerator();

 

        // copy all keys that currently exist in Cache

        while (enumerator.MoveNext())

        {

            keys.Add(enumerator.Key.ToString());

        }

 

        // delete every key from cache

        for (int i = 0; i < keys.Count; i++)

        {

            Cache.Remove(keys[i]);

        }

    }


At first glimpse of this method one could ask why did we first copied current key names from Cache, only  to delete them later?
Why not do it all in a single loop?

if you look at this page at MSDN documentation for IDictionaryEnumerator Interface you will see this text:

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 returns the element that it is set to, even if the enumerator is already invalidated.

This means that if we would try to remove items from the Cache directly while enumerating it, we could face Exceptions and unpredictable effects so the only clean way to do this is to first safely copy all the key names that currently exist in Cache into separate list.
Only then we can delete each cache item without worrying about changes in Cache collection (because even if some changes happen while we loop through the copy of key names, this wont affect us, only have in mind that then we wont delete cache items that were created after we retrieved key names).