Clear all Objects from Cache

Date Added: July 30, 2010 08:20 by By Edward
Categories: ASP.NET

Caching is one of the least used but a very powerful feature of ASP.NET. It can save you time and also unnecessary trips to the database. If you need to cache any type of information in ASP.NET such as a DataSet, DataTable, or an ArrayList, you can use the cache. This works a lot like a 'session' or 'application variable', but it has some added cache-related methods as well. Scalable web applications should have the ability to store items, whether data objects, pages, or event parts of a page, in memory. This allows you to avoid recreating information, expensive database calls or even connections to 3rd party web services.

However sometimes you might want to clear all these cached objects in one go for some specific reason. Like I said web applications should be scalable and build towards high-performance. This is where you will need to use the 'Cache.Remove()' method, as the built-in cache object in ASP.NET does not support a 'Cache.Clear()' method.

Here is an example of storing a datatable and in the cache:

DataTable dtCacheExample = new DataTable();
//code here: add rows to datatable
Cache["dtCacheExample"] = dtCacheExample;

ArrayList arrCacheExample = new ArrayList();
//code here: add items to arraylist
Cache["arrCacheExample"] = arrCacheExample;

To clear the cache use the following:

// Retrieve a dictionary enumerator used to iterate through the 
// key settings and their values contained in the cache.
IDictionaryEnumerator CacheEnum = Cache.GetEnumerator;

while (CacheEnum.MoveNext) {
    Cache.Remove(CacheEnum.Key.ToString);
}
Comments are closed

About DasCode.Net

I'm a ASP.NET web developer and code enthusiast. Blogging about everything .Net related.

Code... that's .net