C# 如何清除asp.net中的服务器缓存?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16532146/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 01:14:42  来源:igfitidea点击:

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

c#asp.netvb.netcaching

提问by xarzu

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

如何清除asp.net中的服务器缓存?我发现有两种缓存。有浏览器缓存和服务器缓存。我已经进行了一些搜索,但我还没有找到使用 asp.net(或不使用)清除服务器缓存的清晰、分步指南。

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

(更新)我刚刚了解到此代码隐藏在 VB 中 - Visual Basic(点网)。

回答by Kenneth

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#

ASP.NET 4.5 C# 的语法更正

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

回答by Giorgio Minardi

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

}

回答by Greg

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.

我不确定您想要完成此操作的确切方法。但是有几种方法,一种方法是 Giorgio Minardi 发布的一种方法,它来自这个问题

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.

希望这会有所帮助。

回答by J W

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.

当我遇到这个问题时,我通过向所有缓存条目添加自定义 CacheDependency 来解决它。

This is how the CacheDependency is defined:

这是 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

回答by Pavel Nazarov

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

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

回答by Faisal Pathan

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

回答by Bhushan Shimpi

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

在页面加载事件上添加此代码..即清除缓存的 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")