Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is MemoryCache.AddOrGetExisting for?

The behaviour of MemoryCache.AddOrGetExisting is described as:

Adds a cache entry into the cache using the specified key and a value and an absolute expiration value.

And that it returns:

If a cache entry with the same key exists, the existing cache entry; otherwise, null.

What is the purpose of a method with these semantics? What is an example of this?

like image 578
Dave Hillier Avatar asked Feb 05 '13 00:02

Dave Hillier


People also ask

Should I dispose MemoryCache?

MemoryCache implements IDisposable so you should call Dispose before replacing the old instance.

What is a MemoryCache?

Memory caching (often simply referred to as caching) is a technique in which computer applications temporarily store data in a computer's main memory (i.e., random access memory, or RAM) to enable fast retrievals of that data. The RAM that is used for the temporary storage is known as the cache.

How does MemoryCache work 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.


1 Answers

There are often situations where you only want to create a cache entry if a matching entry doesn't already exist (that is, you don't want to overwrite an existing value).

AddOrGetExisting allows you to do this atomically. Without AddOrGetExisting it would be impossible to perform the get-test-set in an atomic, thread-safe manner. For example:

 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") 

(See also the Interlocked.CompareExchange method, which enables a more sophisticated equivalent at the variable level, and also the wikipedia entries on test-and-set and compare-and-swap.)

like image 195
LukeH Avatar answered Sep 19 '22 15:09

LukeH