35

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).

Jaymin
  • 2,879
  • 3
  • 19
  • 35
xarzu
  • 8,657
  • 40
  • 108
  • 160
  • 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. – millimoose May 13 '13 at 22:28
  • @xarzu Under what circumstances do you want to clear the cache? – Jim Aho Dec 06 '14 at 21:32

7 Answers7

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);
}
Kenneth
  • 28,294
  • 6
  • 61
  • 84
  • +1 @Kenneth, but I think you meant `foreach` and `entry` instead of `de`. – itsme86 May 13 '13 at 22:31
  • Yes, don't know how I did that :-) – Kenneth May 13 '13 at 22:32
  • You beat me to that part of my question, so I knocked it out of my answer. Nice answer. +1 – Greg May 13 '13 at 22:38
  • Wouldn't this approach also have the thread safe problem mentioned in the answer above? – Adrian Rosca Oct 20 '17 at 17:59
  • Our web api app has a List 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, ... ). 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? – StackOverflowUser Mar 28 '18 at 08:26
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
J W
  • 135
  • 1
  • 3
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]);
} 
  • 3
    Adding an explanatory text along with your answer will certainly help other users with similar questions. Please consider adding... – Leonardo Alves Machado Sep 11 '17 at 11:32
  • This is a good solution. Just be mindful of any eviction code you have as it too will be executed when removing each item. – dnp Feb 29 '20 at 01:26
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);

}
Giorgio Minardi
  • 2,765
  • 1
  • 15
  • 11
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.

Community
  • 1
  • 1
Greg
  • 11,302
  • 2
  • 48
  • 79
  • 2
    Yes, and if you reset the server, it will also clear the cache. This is a bit overkill for what the OP wants – Kenneth May 13 '13 at 22:39
  • @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. – Greg May 13 '13 at 22:41
  • 1
    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. – Kenneth May 13 '13 at 22:50
  • this was a nice piece of code to stumble across for other needs. – Valamas Mar 27 '15 at 21:56
  • I've got a more complex example for building Application Pools and Web-Sites with binding using. – Greg Mar 27 '15 at 22:39
  • ahh, i think your sentence ended early via the dreaded enter = post key. My email is in my profile if you need. Cheers – Valamas Mar 27 '15 at 23:51
1

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

Pavel Nazarov
  • 723
  • 6
  • 10
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")
SHR
  • 7,940
  • 9
  • 38
  • 57
Bhushan Shimpi
  • 90
  • 1
  • 10