0

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?

4

2 に答える 2

3

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.

于 2012-05-20T23:26:30.443 に答える
1

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.

于 2012-05-20T23:14:47.500 に答える