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.
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With