3

我的缓存中有两个项目

  1. 钥匙:猫
  2. 键:Animal_Vacinations

现在,Animal_Vacinations对. _ Cat因此,如果缓存项发生任何更改Cat,则缓存项Animal_Vacinations将失效。完美的 :)

好的..现在解决问题。

创建第二个缓存项(即Animal_Vacinations)后,我添加了第三个缓存对象:-

  1. 钥匙:狗

问题是,第二个对象也需要依赖Dog。在创建第二个对象时,它知道它应该依赖哪些项目。所以在这个例子中 Animal_Vacination 对象知道它应该依赖于......

  1. 乔恩斯基特

问题是,如果我尝试将Animal_Vacination具有所有这 4 个依赖项的对象插入缓存,它会失败。没有错误,只是失败了。(即Cache["Animal_Vacination"] == null)。

这样做的原因是,当我插入具有这 4 个依赖项的缓存对象时……但是其中 1 个或更多的依赖项不_exist_ ……它会优雅地失败。

真可惜。

因为在我上面的示例中,缺少的三个对象之一是在添加 2 个对象之后立即添加的。

所以......无论如何都可以将对象添加到缓存中,具有基于键的缓存依赖项,其中尚未创建 1 个或多个依赖项,但稍后可能会创建?

4

2 回答 2

1

我不愿意将此称为答案,因为它做出了许多假设,可能应该首先通过其他问题来澄清,但这里是这样。

假设某处有一段代码负责使用键“Animal_Vacinations”将某些内容添加到缓存中,并且该代码知道“Animal_Vacinations”项依赖于它的其他缓存项,那么该代码应该创建每个必要的缓存键依赖项,包括将 Null 对象添加到缓存中,如有必要,对于尚未在缓存中找到的任何依赖项。

因此,例如,在您给出的示例中,在添加“Animal_Vacinations”之前缓存中已经存在“Cat”,那么负责将“Animal_Vacinations”添加到缓存的逻辑应该检查缓存是否存在每个依赖项项目,即“Cat”、“Dog”、“Bird”、“Jon Skeet”;如果找不到,则应将占位符对象或装箱值(可能是空字符串)添加到该键的缓存中(在这种情况下,用于“Dog”、“Bird”和“Jon Skeet”);一旦缓存中存在所有依赖项,然后创建缓存依赖项并将“Animal_Vacinations”添加到缓存中。(或者,调用 Cache.Add 并为每个必需的依赖键使用占位符对象,

Continuing your example, when subsequent to this activity a real something is added to the cache with the "Dog" key, using Insert instead of Add in order to account for the possibility that the key already exists (as it does in this example), then the replacement of the "Dog" cache item, which was simply a Null value, will trigger the invalidation of the "Animal_Vacinations" cache item per its cache dependency.

于 2009-05-15T01:02:30.770 回答
0

您可以做的是在添加实际项目后添加依赖项。所以它会是这样的:
添加键 Cat
添加键 Animal_Vacinations
添加缓存依赖于 Animal_Vacinations
添加键 Dog
编辑缓存依赖于 Animal_Vacinations 以便它包含狗。
为 Animal_Vacinations添加键 Bird
编辑缓存依赖项,使其包含 Bird,
依此类推...

于 2009-05-14T11:37:14.933 回答