如何在asp.net中清除服务器缓存?

35

如何清除asp.net中的服务器缓存?我发现有两种缓存:浏览器缓存和服务器缓存。我进行了一些搜索,但尚未找到清除使用asp.net(或其他方式)清除服务器缓存的明确、分步指南。

(更新)我刚刚得知此代码后端是VB - Visual Basic(.net)。


1
我会尝试在IIS中重新启动站点,或者重置应用程序池。否则,您可以公开一个页面,手动从缓存中删除所有内容。 - millimoose
在什么情况下您想要清除缓存? - Jim Aho
7个回答

50
你可以循环遍历所有的缓存项并逐一删除:
foreach (System.Collections.DictionaryEntry entry in HttpContext.Current.Cache){
    HttpContext.Current.Cache.Remove(string(entry.Key));
}

ASP.NET 4.5 C#的语法纠正

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

+1 @Kenneth,但是我认为你指的是foreachentry而不是de - itsme86
是的,不知道我怎么做到的 :-) - Kenneth
你比我更快地回答了我的问题,所以我从我的答案中删除了那部分。很好的回答。+1 - Greg
这种方法是否也存在上面答案提到的线程安全问题? - Adrian Rosca
我们的Web API应用程序有一个存储在HttpContext.Current缓存中的对象列表List<object>。如果缓存当前== null,我们会通过一次HttpContext.Current.Cache.Insert(TheCacheKey,our List <object>,...)调用将数据放入缓存中。我们希望提供一个Web API方法,用于清除/重置缓存,以便在需要时可以手动提交。我们在该方法中调用HttpContext.Current.Cache.Remove(TheCacheKey)。它似乎能正常工作。这样做有什么问题吗? - StackOverflowUser

8
迭代存在问题:它不是线程安全的。如果你正在迭代,而缓存被另一个线程访问,你可能会遇到错误。虽然这种情况发生的概率很低,但在高负载应用中仍然是一个问题。另外,有些缓存实现甚至没有提供迭代方法。
此外,如果你要清除缓存项,你不想从应用程序域的每个部分清除所有内容,而只想清除与你相关的内容。
当我面临这个问题时,我通过为所有缓存条目添加自定义CacheDependency来解决了它。
以下是CacheDependency的定义:
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

2
或者只需使用“lock(HttpContext.Current.Cache)”使其线程安全。 - Vortex852456

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
在您的答案中加上一段解释性文本,肯定会帮助其他有类似问题的用户。请考虑添加... - Leonardo Alves Machado
这是一个很好的解决方案。只需注意在删除每个项目时,任何驱逐代码也将被执行。 - dnp

2
你需要删除已添加到缓存中的项目:
var itemsInCache= HttpContext.Current.Cache.GetEnumerator();

while (itemsInCache.MoveNext())
{

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

}

3
枚举器(enumerator)的Key属性值设定在哪里? - SeanMC

2

我不确定您想要实现这个目标的确切方法。但是有几种方法,其中一种是Giorgio Minardi发布的方法,来自于这个问题

其他选择可能是这样的:

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

这将成功地回收您的应用程序池。这将清除缓存。你有几个选择。注意,虽然这将清除缓存,但也会终止任何已存在的会话。

希望这可以帮助你。


2
是的,如果您重置服务器,它也会清除缓存。这对于OP想要的有点过度了。 - Kenneth
@Kenneth 是的,但我不确定他想要如何完成清除操作。或者他会在什么环境中执行它。我想提供一种替代方法,只要他将特定应用程序参数传递给它,它仍然是可行的。它只会清除一个。 - Greg
1
你应该在回答中添加一条注释,说明这样做也会终止所有会话、Application对象中的所有数据以及正在执行的任何请求。 - Kenneth
这是一段很好的代码,对于其他需求来说真是个意外之喜。 - Valamas
我有一个更复杂的示例,用于构建应用程序池和使用绑定的网站。 - Greg
啊,我觉得你的句子因为不幸的回车键而提前结束了。如果需要的话,我的电子邮件在我的个人资料中。祝好。 - Valamas

1

System.Web.HttpRuntime.UnloadAppDomain() - 重新启动 Web 应用程序,清除缓存,重置 CSS/JS 捆绑包


0
在页面加载事件中添加此代码,即可清除缓存的HTTP头。
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")

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接