Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

thread safety concerns for generic parameters on concurrent collections

Tags:

c#

concurrency

When using System.Collections.Concurrent, what should I be aware of for the contained items?

For instance: ConcurrentDictionary<int,HashSet<string>> vs ConcurrentDictionary<int,ConcurrentBag<string>>

The hashset may be desireable because of its behavior... but its not contained in the safe concurrent collections space. So do I need to worry that multiple threads may write to a contained hashset at once... or will those accesses be managed within the context of the concurrent dictionary in a thread safe manner? MSDN states that instance members of HashSet are not guaranteed to be thread safe.

Please explain the implications and provide guidance. Thank you.

like image 668
cocogorilla Avatar asked Dec 28 '25 23:12

cocogorilla


1 Answers

The concurrent collections do no synchronization for access to the contained items. How could they?

For example:

var myValue = myDictionary[myKey];
... I can now do what I want with myValue without the dictionary being aware of it.

In your case you must implement your own synchronization for access to the HashSet.

like image 70
Joe Avatar answered Dec 31 '25 22:12

Joe



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!