httpcontext.current.cache 中的对象列表
有没有办法查看缓存中的所有对象? 我正在动态创建对象,并且需要定期浏览列表以清除不再使用的对象。
Is there a way to look through the cache for all objects in the cache? I'm dynamically creating objects and I need to periodically go through the list to purge out objects I'm no longer using.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
您可以通过对象进行枚举:
You can enumerate through the objects:
是的,您可以基于缓存键建立索引,也可以迭代内容:
Yes, you can either index based on the cache key, or you you can iterate over the contents:
下面是一个 VB 函数,用于循环访问 Cache 并返回 DataTable 表示形式。
Here is a VB function to iterate through the Cache and return a DataTable representation.
这可能有点晚了,但我使用以下代码轻松迭代所有缓存项,并执行一些自定义逻辑以删除名称中包含特定字符串的缓存项。
我提供了 VB.Net 和 C# 两个版本的代码。
VB.Net版本
C#版本
This may be a bit late, but I used the following code to easily iterate over all cache items and perform some custom logic for removal of cache items that contain a certain string in their names.
I have provided both versions of code in VB.Net as well as C#.
VB.Net Version
C# Version
由于您可能希望从
Cache
对象,对其进行迭代(作为IEnumerable
)并不是非常方便,因为这不允许在迭代过程中删除。 但是,鉴于您无法通过索引访问项目,这是唯一的解决方案。然而,一点 LINQ 可以简化问题。 请尝试如下操作:
请注意,迭代中的每个
item
的类型均为DictionaryEntry
。Since you potentially want to be removing items from the
Cache
object, it is not terribly convenient to iterate over it (as anIEnumerable
), since this doesn't allow removal during the iteration process. However, given that you cannot access items by index, it is the only solution.A bit of LINQ can however simplify the problem. Try something like the following:
Note that each
item
in the iteration is of typeDictionaryEntry
.Jeff,您确实应该查找缓存项目的依赖关系。 这是执行此操作的正确方法。 对缓存数据(项目)进行逻辑分组并为组设置依赖关系。 这样,当您需要使整个组过期时,您就会触及这种常见的依赖关系,并且它们都会消失。
我不确定我是否理解对象列表部分。
Jeff, you should really look up dependencies for your cached items. That's the proper way of doing this. Logically group your cached data (items) and setup dependencies for your groups. This way when you need to expire the entire group you touch such common dependency and they're all gone.
I'm not sure I understand the List of Object part.