Question

I like the lock-free operation of the ConcurrentDictionary and use it in two objects:

 ConcurrentDictionary<datetime,myObj> myIndexByDate
 ConcurrentDictionary<myObjSummary, ConcurrentDictionary<int, myObj> myObjectSummary Index

These two objects need to stay in Sync. Is the only way to do this is to use a Lock, thus avoiding all benefits of the Concurrent dictionary?

Was it helpful?

Solution

I would create a custom class with 2 dictionaries and use a lock only on the methods which are susceptible to change the dictionary(Add, Delete).

You don't lose the benefits of the concurrent dictionary as this method require much less code than what you would have to do using normal dictionary.

OTHER TIPS

ConcurrentDictionary is only "thread-safe" on the operations on a particular instance. e.g. while a ConcurrentDictionary.TryAdd() call is being invoked, no other threads can be modifying the collection...

This doesn't mean that while you get an value from one dictionary and add it to another dictionary that the value still exists in the original dictionary while you're adding it to the second.

You probably have an invariant that details that while you're moving one value from one dictionary to the other, no values in the original dictionary can be removed (or at least that value, but that's a little more difficult to guarantee with ConncurrentDictionary.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top