Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Memory Cache or Concurrent Dictionary?

Tags:

.net

caching

wcf

I am looking to implement caching at a request level for a WCF Service. Each request to this service performs a large number of database calls. Think multiple data collectors. We need to allow one data collector to access the information already retrieved by a preceding data collector.

I was looking to use the new .Net 4.0 Memory cache for this by creating a specific instance per request.

Is this a good idea ? Or should I simply use a Dictionary object ?

BTW : The data collection is going to be in parallel, so there will be more complexities around locking but I could use concurrent collections for that as well.

like image 235
Abhinav Gujjar Avatar asked Sep 26 '12 06:09

Abhinav Gujjar


People also ask

When should I use MemoryCache?

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 the cache memory?

Cache is the temporary memory officially termed “CPU cache memory.” This chip-based feature of your computer lets you access some information more quickly than if you access it from your computer's main hard drive.

Is MemoryCache concurrent?

MemoryCache implements a fast in-memory, e.g. in-process, caching for data that are expensive to create and are thread-safe. manner. All items are stored in a concurrent data structure ( System. Collections.

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.


1 Answers

If you don't need some kind of expiration logic, I would suggest using concurrent collections. You can easily implement a single entry caching mechanism combining ConcurrentDictionary and Lazy classes. Here is another link about Lazy and ConcurrentDictionary combination.

If you need your items to expire, then you better use the built-in MemoryCache and implement double-checked locking pattern to guarantee single retrieval of cache items. A ready to go implementation of double checked locking can be found in Locking pattern for proper use of .NET MemoryCache

like image 86
Yiğit Yener Avatar answered Oct 09 '22 09:10

Yiğit Yener