Thursday, December 15, 2011

How to remove all asp.net data cache by c#


Introduction :
Cache feature is a great feature in asp.net. By caching we store data in memory for quick access. As Microsoft eloquently puts it, "Caching is a technique widely used in computing to increase performance by keeping frequently accessed or expensive data in memory. In the context of a Web application, caching is used to retain pages or data across HTTP requests and reuse them without the expense of recreating them."

But many times we want to update our cache for new updates to happen so to remove data cache from memory. the code snippet given below can be used to remove data cache from memory :

Method One :
foreach (DictionaryEntry dCache in HttpContext.Current.Cache)
{
   HttpContext.Current.Cache.Remove(dCache.Key.ToString());
}

Method Two :

IDictionaryEnumerator cacheEnumerator = HttpContext.Current.Cache.GetEnumerator();

while (cacheEnumerator.MoveNext())
{
  HttpContext.Current.Cache.Remove(cacheEnumerator.Key.ToString());
}

We need these two namespaces to perform this task as Generics is used

using System.Collections;
using System.Collections.Generic;


Conclusion:
These methods are used to remove data cache from memory it won't remove other cache like output or others .....