Question

For a concurrent dictionary

ConcurrentDictionary<string, C> dic;

(Where C is some class), does anyone know of a reference for the rules and restrictions for how one should perform operations on an instance of C, say C0, that is a value in the dictionary? Ie if we have one thread performing operations on C0 directly and another two threads performing operations on C0 via the dictionary, I would guess we could still potentially suffer race conditions? (We wouldn't if C was a primitive).

Thanks for any pointers you can suggest!

Best, Chris

Was it helpful?

Solution

The ConcurrentDictionary class itself is thread-safe.

That has nothing to do wit the thread-safety of whatever you put in the dictionary.

You should make sure that your classes are thread-safe, or, ideally, immutable.

If you do mutate objects in the dictionary, you must also be aware that a different thread might remove or replace it at any time.

In short, thread-safety is still hard; you still need to know exactly what might change and make sure that every thread can handle it.

For more information about writing thread-safe objects, see my blog.

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