theateist
theateist

Reputation: 14399

Does my use of Dictionary require locking?

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?

  1. summary[key] = new List<Result>()
  2. 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

Answers (3)

user1088520
user1088520

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

user703016
user703016

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

Marcel N.
Marcel N.

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

Related Questions