ekflame
ekflame

Reputation: 193

c# when I use only TryGetValue on dictionary.. it's thread-safe?

When init-time, I added some values to my dictionary.

After that, I only need to TryGetValue.

in this case, I need to lock for TryGetValue?

Upvotes: 2

Views: 2395

Answers (2)

Murray Foxcroft
Murray Foxcroft

Reputation: 13745

Reading a Dictionary after population is thread safe.

Use the ConcurrentDictionary Class to ensure thread safety for use cases when you need to read and write.

From MSDN:

Represents a thread-safe collection of key/value pairs that can be accessed by multiple threads concurrently.

Namespace:
System.Collections.Concurrent Assembly: mscorlib (in mscorlib.dll)

Link to MSDN here.

Upvotes: 1

Tim Schmelter
Tim Schmelter

Reputation: 460018

Yes, it's thread safe if you only read it/ use TryGetValue:

Documentation:

A Dictionary<TKey, TValue> 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: 3

Related Questions