0

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

Chris W
  • 145
  • 1
  • 2
  • 12

1 Answers1

2

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.

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
  • Hi, thanks for replying and confirming that the issue is the thread safety of the elements of the dictionary. But since this is the case, isn't I4V right in writing "use sync primitives like lock in C"? – Chris W Aug 19 '13 at 15:06
  • Also, the reason why I said "We wouldn't if C was a primitive" is because then C is not referencable without accessing it directly though the dictionary (and therefore necessarily threadsafe because the dictionary is). Is this not correct? - Thanks – Chris W Aug 19 '13 at 15:12
  • @ChrisW: Yes, but that still limits the purpose of the concurrency. – SLaks Aug 19 '13 at 15:30
  • @ChrisW: Not at all. If you have a mutable reference type that is only referenced by the dictionary, it still isn't thread-safe. What you're trying to say is that immutable types are thread-safe. – SLaks Aug 19 '13 at 15:32
  • One last question - you say "[locks] limits the purpose of the concurrency." - do you mean that "concurrency = threadsafe + fast" and that locks aren't fast? – Chris W Aug 19 '13 at 15:40
  • @ChrisW: No. Concurrency means doing multiple things at once. The whole point of a lock is to prevent you from doing multiple things at once. – SLaks Aug 19 '13 at 16:20
  • Ok, I had thought that internally, the concurrent classes must have done something equivalent to locking anyway, is that incorrect? – Chris W Aug 19 '13 at 17:14
  • @ChrisW: No; the concurrent collections use lock-free algorithms. This is why it's [1k+ lines](http://www.dotnetframework.org/default.aspx/4@0/4@0/untmp/DEVDIV_TFS/Dev10/Releases/RTMRel/ndp/clr/src/BCL/System/Collections/Concurrent/ConcurrentDictionary@cs/1305376/ConcurrentDictionary@cs). – SLaks Aug 19 '13 at 17:26