基于依赖关键字清除缓存

时间:2014-05-28 01:20:49

标签: .net vb.net caching

根据日期时间值,我将值插入缓存中:

Dim Value1 As String = "value1"
Dim Value2 As String = "value2"
Dim Key1 As String = "Key" & New Date(2014, 1, 1, 1, 1, 0).ToString
Dim Key2 As String = "Key" & New Date(2014, 1, 1, 1, 2, 0).ToString
HttpContext.Current.Cache.Insert(Key1, Value1)
HttpContext.Current.Cache.Insert(Key2, Value2)

是否可以使用另一个缓存项作为CacheDependency使这些缓存项无效?

我尝试了以下内容,但这不起作用:

Dim Keys As String() = New String(0) {}
Keys(0) = "OtherKey"
Dim MyDependency As New System.Web.Caching.CacheDependency(Nothing, Keys)
HttpContext.Current.Cache.Insert(Key1, Value1, MyDependency)
HttpContext.Current.Cache.Insert(Key2, Value2, MyDependency)

'To clear all cache items:
HttpContext.Current.Cache.Remove("OtherKey")

当我使用它时(没有remove语句),永远不能在缓存中找到这些项。我在这里做错了什么?

1 个答案:

答案 0 :(得分:3)

如果要将CacheDependency用于另一个缓存键:

  • 您必须在缓存中找到您所依赖的密钥(即 OtherKey )(请参阅this article)。否则,您的商品将无法在缓存中找到。
  • 您需要为每个项目创建不同的CacheDependency实例。否则,您将收到错误An attempt was made to reference a CacheDependency object from more than one Cache entry(请参阅this question的答案)

因此,插入项目的代码将是这样的:

' Make sure OtherKey is found in the cache
HttpContext.Current.Cache.Insert("OtherKey", "SomeValue")

' Add the items with a different CacheDependency instance per item
Dim Keys As String() = New String(0) {}
Keys(0) = "OtherKey"
HttpContext.Current.Cache.Insert(Key1, Value1, New System.Web.Caching.CacheDependency(Nothing, Keys))
HttpContext.Current.Cache.Insert(Key2, Value2, New System.Web.Caching.CacheDependency(Nothing, Keys))
  • 请注意,如果您未使用密钥 OtherKey 添加缓存项目,则永远不会找到相关项目。

然后,当您从缓存中删除OtherKey时,将自动删除相关项。因此,此行会自动从缓存中删除 Key1 Key2

HttpContext.Current.Cache.Remove("OtherKey")

希望它有所帮助!