Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 816
Storm Avatar asked Jan 15 '12 08:01

Storm


People also ask

What does in-memory cache mean?

What is an In-Memory Cache? An in-memory cache is a data storage layer that sits between applications and databases to deliver responses with high speeds by storing data from earlier requests or copied directly from databases.

What is memory cache in C#?

In-Memory Cache is used for when you want to implement cache in a single process. When the process dies, the cache dies with it. If you're running the same process on several servers, you will have a separate cache for each server. Persistent in-process Cache is when you back up your cache outside of process memory.

Is Memorycache thread safe?

So it is "safe" for multi threaded apps like web sites, but that does not mean it guarantees to only execute the delegate to prime the cache only once.


1 Answers

Add does nothing (returns false) if there is already a value for that key. Set does an insert or update, as necessary.

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 end result as Remove + Add, the mechanism difference is important since it could impact other callers.

For example of Add:

Return Value

Type: System.Boolean true if insertion succeeded, or false if there is an already an entry in the cache that has the same key as key.

like image 71
Marc Gravell Avatar answered Sep 20 '22 19:09

Marc Gravell