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?
MemoryCache implements IDisposable so you should call Dispose before replacing the old instance.
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.
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.
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.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With