2

Based on a datetime value I insert values into the cache:

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)

Is it possible to invalidate those cache items using another cache item as CacheDependency?

I tried the following, but this doesn't work:

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")

When I use this (without the remove statement), the items never can be found in the cache. What am I doing wrong here?

Kirk Woll
  • 76,112
  • 22
  • 180
  • 195
Martin de Ruiter
  • 515
  • 1
  • 6
  • 25

1 Answers1

3

If you want to use a CacheDependency for another cache key:

  • The key you depend on (ie OtherKey) must be found in the cache (See this article). Otherwise your items will not be found in the cache.
  • You need to create a different CacheDependency instance per item. Otherwise you will get the error An attempt was made to reference a CacheDependency object from more than one Cache entry (See the answer to this question)

So your code to insert the items would be something like this:

' 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))
  • Please note that if you donĀ“t add the cache item with key OtherKey, the dependent items will never be found.

Then when you remove OtherKey from the cache, the dependent items will be automatically removed. So this line would automatically remove both Key1 and Key2 from the cache:

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

Hope it helps!

Community
  • 1
  • 1
Daniel J.G.
  • 34,266
  • 9
  • 112
  • 112