根据日期时间值,我将值插入缓存中:
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语句),永远不能在缓存中找到这些项。我在这里做错了什么?
答案 0 :(得分:3)
如果要将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时,将自动删除相关项。因此,此行会自动从缓存中删除 Key1 和 Key2 :
HttpContext.Current.Cache.Remove("OtherKey")
希望它有所帮助!