20

I have the following ConcurrentDictionary:

ConcurrentDictionary<Guid, Session> sessions;

I know that sessions.TryGetValue(key, out session) is thread-safe, but my question is if sessions[key] is also thread-safe?

sessions.TryGetValue(key, out session) returns true or false depending on whether it was able to get the value or not.

Will sessions[key] return null if it is unable to get the value? I would think so. Can anyone confirm or shed more light on this? Thanks.

crush
  • 16,713
  • 9
  • 59
  • 100

1 Answers1

19

It is thread-safe, but it will not return null.

The documentation clearly states:

Exceptions

KeyNotFoundException
The property is retrieved and key does not exist in the collection.

Community
  • 1
  • 1
SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
  • Can you give me a link to this in the documentation, I was unable to find it. Thanks! – crush Jun 13 '13 at 13:32
  • Thanks for the quick answer! I see it is mapped to the `Item` collection. That makes sense now. I was unsure how to find this in the documentation before. – crush Jun 13 '13 at 13:33
  • How is that clear? It only states that an exception is thrown if the key does not exist. But what happens if right at that time another thread is modifying the item at that key ? – Chris Jun 16 '15 at 18:54
  • 5
    @Chris: The whole point of the class is to be thread-safe; all operations are atomic. The documentation explicitly states `All public and protected members of ConcurrentDictionary are thread-safe and may be used concurrently from multiple threads. However, members accessed through one of the interfaces the ConcurrentDictionary implements, including extension methods, are not guaranteed to be thread safe and may need to be synchronized by the caller.` – SLaks Jun 16 '15 at 18:57
  • 1
    @SLaks: So, since indexer property `TValue this[ TKey key ]` is implementation of `IDictionary`'s one, it is not guaranted to be thread safe. Why do you say it is? – BlackOverlord Apr 06 '18 at 12:04
  • 2
    @BlackOverlord: That says "members accessed through one of the interfaces", not members defined by an interface. In other words, explicit interface implementations. – SLaks Apr 08 '18 at 21:02