Reputation: 14399
Many threads have access to summary
. Each thread will have an unique key for accessing the dictionary;
Dictionary<string, List<Result>> summary;
Do I need locking for following operations?
summary[key] = new List<Result>()
summary[key].Add(new Result());
It seems that I don't need locking because each thread will access dictionary with different key, but won't the (1) be problematic because of adding concurrently new record to dictionary with other treads?
Upvotes: 4
Views: 228
Reputation:
By default Dictionary is not thread safe. It does not matter what are you going to add. And the most important: you cannot control concurrent additions from different threads. So you need locks for sure. Or switch to a thread safe collection (i.e. CocnurrentDictionary for .NET 4+)
Upvotes: 0
Reputation: 37945
All write accesses to your dictionnary must be locked. There is no guarantee that accessing different keys is thread safe, and, in fact, it isn't.
From MSDN:
A Dictionary can support multiple readers concurrently, as long as the collection is not modified. Even so, enumerating through a collection is intrinsically not a thread-safe procedure. In the rare case where an enumeration contends with write accesses, the collection must be locked during the entire enumeration. To allow the collection to be accessed by multiple threads for reading and writing, you must implement your own synchronization.
Upvotes: 2
Reputation: 13976
Yes, you need to use locking.
Dictionary is not thread safe for add operations. If you are on .NET 4 you may consider switching to ConcurrentDictionary. Otherwise you should create your own thread safe collection (such as this).
Consider using a ReaderWriterLockSlim for synchronizing access to your collection (in case you won't use ConcurrentDictionary).
Upvotes: 5