What's the difference between MemoryCache.Add and MemoryCache.Set?

I read the MSDN documentation but didn't really understand it.

I believe that the behavior of Set is "replace existing, or add" (atomically).

Is that correct?

28401 次浏览

如果已经有该键的值,则 Add不执行任何操作(返回 false)。Set根据需要进行插入或更新。

Remove + Add would leave a gap in the middle when another thread querying that key would get no clue (Set does not; the swap is typically atomic); as such, while Set has the same 最终结果 as Remove + Add, the mechanism difference is important since it could impact other callers.

For example of :

Return Value

类别: 系统。如果插入成功,则为布尔值 true; 如果缓存中已经有一个条目与键具有相同的键,则为布尔值 false。