Search code examples
.netwcfcaching

Memory Cache or Concurrent Dictionary?


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.


Solution

  • 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