Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ConcurrentDictionary TryGetValue vs []. Is [] still thread-safe?

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.

like image 892
crush Avatar asked Jun 13 '13 13:06

crush


People also ask

Is TryGetValue thread-safe in ConcurrentDictionary?

TryGetValue itself is thread-safe... it does not make the if statement thread-safe... in the example your show you need the lock . Thanks for clearing that up.

Is ConcurrentDictionary thread-safe?

Concurrent. ConcurrentDictionary<TKey,TValue>. This collection class is a thread-safe implementation. We recommend that you use it whenever multiple threads might be attempting to access the elements concurrently.

Is ConcurrentDictionary indexer thread-safe?

It is thread-safe in the sense that the internal state of the ConcurrentDictionary will not be corrupted. This is the main guarantee offered by this class.

Is ConcurrentDictionary Addorupdate thread-safe?

ConcurrentDictionary is thread-safe collection class to store key/value pairs. It internally uses locking to provide you a thread-safe class. It provides different methods as compared to Dictionary class. We can use TryAdd, TryUpdate, TryRemove, and TryGetValue to do CRUD operations on ConcurrentDictionary.


1 Answers

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.

like image 55
SLaks Avatar answered Oct 27 '22 13:10

SLaks