I have just come across the MemoryCache which is new in .NET 4.
I get that it can be useful if you want to:
Are there any other compelling reasons to use a MemoryCache over a standard Dictionary<string,object>
I have a few books on C# and .NET and there is no reference to it anywhere.
This is used for the short term. It's for when we have used data in our application or some time after, you have to remove the cache data from our system, then we can use it. This is used for data outside of the cache, like if you saved the data in a file or database and then want to use it in our application.
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.
Caching makes a copy of data that can be returned much faster than from the source. Apps should be written and tested to never depend on cached data. ASP.NET Core supports several different caches. The simplest cache is based on the IMemoryCache. IMemoryCache represents a cache stored in the memory of the web server.
I think you nailed the two compelling reasons :-)
The MemoryCache has an eviction strategy, so that it can throw out entries that are no longer needed or for that you do not have enough memory anymore.
A Dictionary will not "lose contents".
Update: MemoryCache is thread-safe and has methods such as AddOrGetExisting. With a Dictionary, you'd have to synchronize access yourself (or use ConcurrentDictionary).
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