The indexer will find the pair represented by the given key, add it if it doesn't exist, and replace the value with the given value if it does exist. This operation is logically "atomic" from the point of view of the dictionary. You don't need to worry about the dictionary being corrupted when multiple threads access the dictionary through its indexer concurrently.
Add
is hidden because you should generally be using TryAdd
instead. Adding could fail if that key is added by another thread after you check if the key exists. This is of course not an issue for the indexer. If another thread adds the item before the current thread does, it'll just overwrite the value, rather than throwing an exception.
AddOrUpdated
takes a function for the update for two reasons:
- It can use the previous value to determine the updated value.
- It's possible that generating the updated value will have side effects, or be an expensive computation. Making it a function allows this operation to be deferred until you know that you do in fact need to update an item.