MemoryCache.AddOrGetExisting的行为描述如下:
使用指定的键、值和绝对过期时间将缓存条目添加到缓存中。
它的返回结果是:
如果具有相同键的缓存条目存在,则为现有缓存条目;否则为 null。
这种语义方法的目的是什么?这有什么例子吗?
MemoryCache.AddOrGetExisting的行为描述如下:
使用指定的键、值和绝对过期时间将缓存条目添加到缓存中。
它的返回结果是:
如果具有相同键的缓存条目存在,则为现有缓存条目;否则为 null。
这种语义方法的目的是什么?这有什么例子吗?
有时候您只想在不存在匹配条目的情况下创建缓存项(也就是说,您不想覆盖现有值)。
AddOrGetExisting
可以让您原子性地执行此操作。如果没有 AddOrGetExisting
,将无法以原子、线程安全的方式执行获取-测试-设置。例如:
Thread 1 Thread 2
-------- --------
// check whether there's an existing entry for "foo"
// the call returns null because there's no match
Get("foo")
// check whether there's an existing entry for "foo"
// the call returns null because there's no match
Get("foo")
// set value for key "foo"
// assumes, rightly, that there's no existing entry
Set("foo", "first thread rulez")
// set value for key "foo"
// assumes, wrongly, that there's no existing entry
// overwrites the value just set by thread 1
Set("foo", "second thread rulez")
(另请参见Interlocked.CompareExchange
方法,该方法可在变量级别上进行更复杂的等效操作,还有关于test-and-set和compare-and-swap的维基百科条目。)
Add
呢?总是使用 AddOrGetExisting
不是更好吗? - JozeAddOrGetExisting
实际上不会更新现有的缓存条目。AddOrGetExisting
发现一个现有的缓存条目时,它不会处理传递给调用的CachePolicy。如果您使用自定义更改监视器设置昂贵的资源跟踪机制,这可能会有问题。通常,在缓存条目被驱逐时,缓存系统会调用Dipose()
您的ChangeMonitors。这为您提供了取消注册事件等操作的机会。然而,当AddOrGetExisting
返回现有条目时,您必须自己处理。Add
方法或调用AddOrGetExisting
。 - springy76我实际上没有使用过这个功能,但我猜想一种可能的使用情况是,如果您想无条件地使用新条目更新缓存中特定键的条目,并且您想显式处理返回的旧条目。