如何在asp.net中清除服务器缓存?
如何在asp.net中清除服务器缓存? 我发现有两种缓存。 有浏览器缓存和服务器缓存。 我已经做了一些搜索,但我还没有找到一个清晰的,逐步指导清除服务器缓存使用asp.net(或不)。
(更新)我刚学会了这个代码隐藏在VB – Visual Basic(dot net)中。
您可以循环遍历所有缓存项并逐个删除它们:
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); }
迭代存在问题:它不是线程安全的。 如果您正在迭代,并且从另一个线程访问缓存,则可能会收到错误。 这种可能性很低,但这对高负载应用来说是一个问题。 仅供参考,一些缓存实现甚至不提供迭代方法。
此外,如果要清除缓存项目,则不希望清除应用程序域的每个部分中的所有内容,而是清除与您相关的内容。
当我遇到这个问题时,我通过向所有缓存条目添加自定义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 dep_list = new List (); 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
我不确定您希望实现此目标的确切方法。 但有几种方法,一种方式是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"); } }
这将成功回收您的应用程序池。 哪个会清除缓存。 你有几个选择。 请注意,虽然这将清除缓存,但它也将终止任何存在的会话。
希望这会有所帮助。
您需要删除已添加到缓存中的项目:
var itemsInCache= HttpContext.Current.Cache.GetEnumerator(); while (itemsInCache.MoveNext()) { HttpContext.Current.Cache.Remove(enumerator.Key); }
System.Web.HttpRuntime.UnloadAppDomain() – 重启Web应用程序,清除缓存,重置css / js包
上述就是C#学习教程:如何在asp.net中清除服务器缓存?分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!
public void ClearCacheItems() { List keys = new List (); IDictionaryEnumerator enumerator = Cache.GetEnumerator(); while (enumerator.MoveNext()) keys.Add(enumerator.Key.ToString()); for (int i = 0; i < keys.Count; i++) Cache.Remove(keys[i]); }
本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。
ctvol管理联系方式QQ:251552304
本文章地址:https://www.ctvol.com/cdevelopment/959958.html