从缓存中删除特定项目(ASP.NET) [英] Removing specific items from Cache (ASP.NET)

查看:115
本文介绍了从缓存中删除特定项目(ASP.NET)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我添加了一堆物品ASP.NET缓存与特定的preFIX的。
我希望能够遍历缓存,并删除这些项目。

I am adding a bunch of items to the ASP.NET cache with a specific prefix. I'd like to be able to iterate over the cache and remove those items.

我试图做到这一点的方法是,像这样:

The way I've tried to do it is like so:

    foreach (DictionaryEntry CachedItem in Cache)
    {
        string CacheKey = CachedItem.Key.ToString();
        if(CacheKey.StartsWith(CACHE_PREFIX){
            Cache.Remove(CacheKey);
        }
    }

我能得到这个更有效地做什么?

Could I be doing this more efficiently?

我曾考虑创建一个临时文件并与依赖关系的文件中添加的项目,然后只需删除该文件。那是在杀人?

I had considered creating a temp file and adding the items with a dependancy on the file, then just deleting the file. Is that over kill?

推荐答案

您不能从一个集合,而你迭代它删除的项目,所以你需要做的是这样的:

You can't remove items from a collection whilst you are iterating over it so you need to do something like this:

List<string> itemsToRemove = new List<string>();

IDictionaryEnumerator enumerator = Cache.GetEnumerator();
while (enumerator.MoveNext())
{
    if (enumerator.Key.ToString().ToLower().StartsWith(prefix))
    {
        itemsToRemove.Add(enumerator.Key.ToString());
    }
}

foreach (string itemToRemove in itemsToRemove)
{
    Cache.Remove(itemToRemove);
}

这方法很好,比缓存依赖更快,更容易。

This approach is fine and is quicker and easier than cache dependencies.

这篇关于从缓存中删除特定项目(ASP.NET)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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