Jos*_*eph 1 asp.net caching asp.net-2.0
我为我正在开发的网站创建了自己的缓存管理器,我希望在某些情况下找到清除缓存的最佳方法.
我发现很多文章说清除缓存的正确方法是调用HttpRuntime.Close()
但是,在我的单元测试设置中,我调用封装函数HttpRuntime.Close(),并且不会清除缓存.
我期望它能够执行类似的操作
foreach (DictionaryEntry cacheItem in HttpRuntime.Cache)
{
HttpRuntime.Cache.Remove(cacheItem.Key.ToString());
}
Run Code Online (Sandbox Code Playgroud)
foreach循环在我的封装函数中运行良好,但Close()永远不会正常工作.
我是否误解了HttpRuntime.Close()的目的,还是有更邪恶的事情发生在这里?
不要使用Close,它比文档说的更多.文档还说在处理正常请求时不要使用它...
这是Close()的反映源:
[SecurityPermission(SecurityAction.Demand, Unrestricted=true)]
public static void Close() {
if (_theRuntime.InitiateShutdownOnce()) {
SetShutdownReason(ApplicationShutdownReason.HttpRuntimeClose, "HttpRuntime.Close is called");
if (HostingEnvironment.IsHosted) {
HostingEnvironment.InitiateShutdown();
} else {
_theRuntime.Dispose();
}
}
}
Run Code Online (Sandbox Code Playgroud)
此外,您不能迭代集合并同时从中删除项目,因为这会使枚举无效.
所以,试试这个,这不会改变它循环的内容:
List<string> toRemove = new List<string>();
foreach (DictionaryEntry cacheItem in HttpRuntime.Cache) {
toRemove.Add(cacheItem.Key.ToString());
}
foreach (string key in toRemove) {
HttpRuntime.Cache.Remove(key);
}
Run Code Online (Sandbox Code Playgroud)
实际上,您应该尝试使用缓存依赖关系来自动清除无效的缓存条目,然后这一切都变得不必要了.
| 归档时间: |
|
| 查看次数: |
5050 次 |
| 最近记录: |