What is MemoryCache.AddOrGetExisting for?

Dave Hillier picture Dave Hillier · Feb 5, 2013 · Viewed 12.4k times · Source

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?

Answer

LukeH picture LukeH · Feb 5, 2013

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