How do I clear the server cache in asp.net?

2020-02-08 10:26发布

问题:

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

回答1:

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);
}


回答2:

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


回答3:

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.



回答4:

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]);
} 


回答5:

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

}


回答6:

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



回答7:

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