asp.net - 为什么 Cache.Add 返回一个表示缓存项的对象?

标签 asp.net caching

From MSDN关于在 ASP.NET 缓存中添加或插入项目之间的差异:

Note: The Add and Insert methods have the same signature, but there are subtle differences between them. First, calling the Add method returns an object that represents the cached item, while calling Insert does not. Second, their behavior is different if you call these methods and add an item to the Cache that is already stored there. The Insert method replaces the item, while the Add method fails. [emphasis mine]

第二部分很简单。毫无疑问。

但是对于第一部分,为什么它要返回一个表示缓存项的对象?如果我尝试将一个项目添加到缓存中,我已经拥有/知道该项目是什么?

我不明白。这背后的原因是什么?

最佳答案

在缓存上调用 Add() 最终会调用具有以下签名的内部方法:

internal abstract CacheEntry UpdateCache(CacheKey cacheKey, 
    CacheEntry newEntry, bool replace, CacheItemRemovedReason removedReason, 
    out object valueOld);

注意out object valueOld - 它被设置为当前位于缓存中“cacheKey”位置的对象,并作为 Add() 的结果返回。该文档具有误导性,它实际上不是返回的同一个对象 - 它是位于该相同键位置的任何对象。

这可以通过以下代码轻松验证:

 String x = "lorem";
 String y = "ipsum";

 HttpContext.Current.Cache.Add("hi", x, null, DateTime.MaxValue, 
                               Cache.NoSlidingExpiration, 
                               CacheItemPriority.Normal, null);

 var z = HttpContext.Current.Cache.Add("hi", y, null, DateTime.MaxValue,
                              Cache.NoSlidingExpiration, 
                              CacheItemPriority.Normal, null);

 //Result:
 //   z == "lorem"

关于asp.net - 为什么 Cache.Add 返回一个表示缓存项的对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1286359/

相关文章:

asp.net - 使用IIs6或IIs7的命令行在IIS中更改虚拟目录或站点的物理路径

java - Spring中的自动缓存失效

java - Vaadin 8 - 应用程序范围的缓存

iphone - 在 iPhone 上缓存整个网页

c - 缓存行开头的变量

ios - 了解核心视频 CVPixelBufferPool 和 CVOpenGLESTextureCache 语义

javascript - 无法加载资源: the server responded with a status of 405 (Method Not Allowed)

c# - 如何在 jQuery/JavaScript 中编码 URL 并在 ASP.NET 中解码

javascript - 数据切换和数据目标未按预期工作

C# 无法在自定义验证属性中找到其他属性