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