Reputation: 5220
Currently I have some async methods that all trying to update and read from a Dictionary
Side question:
Can the async functions cause KeyNotFoundException and NullReferenceException?
I am just doing
_dictonary[myString] = myObject
Anyways. I would like to replace all Dictionary<string,object>
with ConcurrentDictionary<string, object
> . I don't care at all whether some thread get the data right before/after another thread write into it.
Is there any trouble I can get into if I just do a text replace all Dictionary
with ConcurrentDictionary
and it compiles successfully?
Upvotes: 0
Views: 50
Reputation: 38727
Internally ConcurrentDictionary
's indexer method uses TryGetValue
and the same TryAddInternal
as TryAdd
does.
Setting a value shouldn't throw an exception unless your key is null. It should work as you expect (although another thread could come in and change it before you read it again).
You will still get a KeyNotFoundException
if the key isn't found in the dictionary. There could be timing issues if you expect one thread to insert a value, and then you try and read it using concurrentDictionary[key]
. I'd recommend using TryGetValue
if you want safety in this respect.
Upvotes: 2