36

How do I clear the server cache in asp.net? I have found out that there are two kinds of the cache. There is the browser cache and the server cache. I have done some searching but I have yet to find a clear, step-by-step guide for clearing the server cache using asp.net (or not).

(update) I just learned that the code-behind for this is in VB - Visual Basic (dot net).

2
  • 1
    I'd try restarting the site in IIS, or maybe recycling the application pool. Otherwise you could expose a page that manually deletes everything from the cache. Commented May 13, 2013 at 22:28
  • @xarzu Under what circumstances do you want to clear the cache? Commented Dec 6, 2014 at 21:32

7 Answers 7

50

You could loop through all the cache items and delete them one by one:

foreach (System.Collections.DictionaryEntry entry in HttpContext.Current.Cache){
    HttpContext.Current.Cache.Remove(string(entry.Key));
}

Syntax Correction for ASP.NET 4.5 C#

foreach (System.Collections.DictionaryEntry entry in HttpContext.Current.Cache){
    HttpContext.Current.Cache.Remove((string)entry.Key);
}
Sign up to request clarification or add additional context in comments.

5 Comments

+1 @Kenneth, but I think you meant foreach and entry instead of de.
Yes, don't know how I did that :-)
You beat me to that part of my question, so I knocked it out of my answer. Nice answer. +1
Wouldn't this approach also have the thread safe problem mentioned in the answer above?
Our web api app has a List<object> list of objects stored in a HttpContext.Current cache. We place the data in the cache (if the cache is currently == null) through a single invoke of HttpContext.Current.Cache.Insert( TheCacheKey, our List<object>, ... ). We wanted to provide ourselves a web api method that cleared/reset that cache that we could manually submit if we wanted to. We are invoking HttpContext.Current.Cache.Remove( TheCacheKey ) in the method. It appears to work. Is there something wrong with doing this?
8

There is a problem with iteration: it's not thread safe. If you are iterating, and the cache gets accessed from another thread, you might be getting an error. The probability of this is low, but it's a problem with high load applications. FYI, some cache implementations don't even provide iteration methods.

Also, if you are clearing your cache items, you don't want to clear everything from every part of the app domain, but just what's related to you.

When I faced this problem, I solved it by adding a custom CacheDependency to all my cache entries.

This is how the CacheDependency is defined:

public class CustomCacheDependency : CacheDependency
{
    //this method is called to expire a cache entry:
    public void ForceDependencyChange()
    {
        this.NotifyDependencyChanged(this, EventArgs.Empty);
    }
}

//this is how I add objects to cache:
HttpContext.Current.Cache.Add(key, //unique key 
            obj, 
            CreateNewDependency(), //the factory method to allocate a dependency
            System.Web.Caching.Cache.NoAbsoluteExpiration,
            new TimeSpan(0, 0, ExpirationInSeconds),
            System.Web.Caching.CacheItemPriority.Default,
            ReportRemovedCallback);

//A list that holds all the CustomCacheDependency objects:
#region dependency mgmt
private List<CustomCacheDependency> dep_list = new List<CustomCacheDependency>();

private CustomCacheDependency CreateNewDependency()
{
        CustomCacheDependency dep = new CustomCacheDependency();
        lock (dep_list)
        {
            dep_list.Add(dep);
        }
        return dep;
}

//this method is called to flush ONLY my cache entries in a thread safe fashion:
private void FlushCache()
{
        lock (dep_list)
        {
            foreach (CustomCacheDependency dep in dep_list) dep.ForceDependencyChange();
            dep_list.Clear();
        }
} 
#endregion

1 Comment

Or just use "lock(HttpContext.Current.Cache)" to make it thread safe.
3
public void ClearCacheItems()
{
   List<string> keys = new List<string>();
   IDictionaryEnumerator enumerator = Cache.GetEnumerator();

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

   for (int i = 0; i < keys.Count; i++)
      Cache.Remove(keys[i]);
} 

2 Comments

Adding an explanatory text along with your answer will certainly help other users with similar questions. Please consider adding...
This is a good solution. Just be mindful of any eviction code you have as it too will be executed when removing each item.
2

You'll need to remove the items you've added to the cache:

var itemsInCache= HttpContext.Current.Cache.GetEnumerator();

while (itemsInCache.MoveNext())
{

    HttpContext.Current.Cache.Remove(enumerator.Key);

}

1 Comment

where is the value of enumerator.Key set?
2

I'm not sure of the exact methodology in which you would like to accomplish this. But there are a few ways, one way is the one Giorgio Minardi posted which comes from this question.

The other choices could be like this:

using Microsoft.Web.Administration;

public bool RecycleApplicationPool(string appPoolName)
{

    try
    {
        using (ServerManager iisManager = new ServerManager())
        {
             iisManager.ApplicationPools[appPoolName].Recycle();
             return true;
        }
    }
    catch (Exception ex)
    {
        throw new Exception("Unhandled Exception");
    }
}

That will successfully recycle your application pool. Which would clear the cache. You've got a few choices. Beware, though this will clear the cache it will also terminate any sessions that exists.

Hopefully this helps.

6 Comments

Yes, and if you reset the server, it will also clear the cache. This is a bit overkill for what the OP wants
@Kenneth Yeah, but I wasn't sure how he wanted to accomplish the clear. Or what environment he would do it in. Thought I'd give an alternative approach that is still viable, as long as he passes the specific application parameter into it. It would only clear the one.
You should add a note to your answer that with this you're also killing any sessions, all the data you have in the Application-object and any requests that are executing.
this was a nice piece of code to stumble across for other needs.
I've got a more complex example for building Application Pools and Web-Sites with binding using.
|
1

System.Web.HttpRuntime.UnloadAppDomain() - restarts web application, clears cache, resets css/js bundles

Comments

0

add this code on page load event ..that is http headers to clear cache.

Response.CacheControl = "private"
Response.CacheControl = "no-cache"
Response.ClearHeaders()
Response.AppendHeader("Cache-Control", "no-cache")        
Response.AppendHeader("Cache-Control", "private")            
Response.AppendHeader("Cache-Control", "no-store")          
Response.AppendHeader("Cache-Control", "must-revalidate")          
Response.AppendHeader("Cache-Control", "max-stale=0")           
Response.AppendHeader("Cache-Control", "post-check=0")           
Response.AppendHeader("Cache-Control", "pre-check=0")      
Response.AppendHeader("Pragma", "no-cache")
Response.AppendHeader("Keep-Alive", "timeout=3, max=993")          
Response.AppendHeader("Expires", "Mon, 26 Jul 2006 05:00:00 GMT")

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.