Locking during AddOrUpdate alone will not help - you still have to block every time you read from the set.
If you intend to treat this collection as thread safe, you really need values ββthat can also be thread safe. You need a ConcurrentSet , ideally. Now this does not exist within the framework (unless I missed something), but you could create your own ConcurrentSet<T> that used ConcurrentDictionary<T, int> (or any other TValue that you like) as your basic data structure. Basically, you ignore the meaning in the dictionary and simply consider the presence of the key as an important part.
You do not need to implement everything that is inside ISet<T> - just the bit that you really need.
Then you would create a ConcurrentDictionary<string, ConcurrentSet<string>> in your application code, and you are absent - there is no need to block.
source share