使用ASP.NET最有效的方式清除缓存 [英] Most Efficient Way Of Clearing Cache Using ASP.NET

查看:741
本文介绍了使用ASP.NET最有效的方式清除缓存的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我建立一个ASP.NET/Umbraco供电的网站,该网站是通过实体框架的驱动很自定义数据,我们有缓存相当多的数据的查询(例如搜索按关键字),因为它是一个繁忙的网站。

I am building an ASP.NET/Umbraco powered website which is very custom data driven via entity framework, we are having to cache quite a lot of the data queries (For example searches by keyword) as it's a busy site.

但是,当用户创建一个新的数据输入,我需要清除所有缓存查询(搜索等),因此新的条目是提供结果。

But when a user creates a new data entry, I need to clear all the cached queries (Searches etc..) so the new entry is available in the results.

所以在我的创建,删除和更新方法我打电话下面的方法:

So in my create, delete and update methods I am calling the following method:

public static void ClearCacheItems()
{
    var enumerator = HttpContext.Current.Cache.GetEnumerator();

    while (enumerator.MoveNext())
    {
        HttpContext.Current.Cache.Remove(enumerator.Key.ToString());
    }
}



这真的是坏?我看不到我应该怎么回事清除缓存的项目?

Is this really bad? I can't see how else I am supposed to clear the cached items?

推荐答案

您使用的方法实际上是正确的方法清除缓存,只有一个小的'错误'在你的代码。枚举的唯一有效只要原始集合的保持不变。因此,尽管代码可能工作的大部分时间,有可能在某些情况下,小的误差。 ,最好是使用下面的代码,这确实基本上是相同的,但不直接使用枚举

The method you use is actually the correct way to clear your cache, there is just one minor 'error' in your code. The enumerator only is valid as long as the original collection remains unchanged. So while the code might work most of the time, there might be small errors in certain situations. Best is to use the following code, which does essentially the same, but does not use the enumerator directly.

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

这篇关于使用ASP.NET最有效的方式清除缓存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆