Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are the compelling reasons to use a MemoryCache over a plain old Dictionary<string,object>

Tags:

c#

.net

caching

I have just come across the MemoryCache which is new in .NET 4.

I get that it can be useful if you want to:

  • Limit the total memory usage of the cache
  • Have an object expiry time (time to live) for objects you put in the cache

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.

like image 640
dodgy_coder Avatar asked Aug 31 '11 01:08

dodgy_coder


People also ask

When should I use MemoryCache?

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.

What is MemoryCache 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.

What is Caching in ASP net Core?

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.


1 Answers

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

like image 177
Thilo Avatar answered Oct 09 '22 03:10

Thilo