Concurrent Dictionary AddOrUpdate vs Index Add

前端 未结 4 470
走了就别回头了
走了就别回头了 2021-02-03 21:06

There are two ways I\'ve assigned values to a existing key in a concurrent dictionary in my current project.

A. concurrentDictionary1[key] = value;

4条回答
  •  时光说笑
    2021-02-03 21:56

    This is an old question, but no one answered why you would use one over the other.

    Choose A (the indexer) if you want to add or update and the update is not dependent on the existing value.

    Choose B (AddOrUpdate) if you want to add or update and the update depends on an existing value. AddOrUpdate will do the update atomically.

    So in the case in the question, you want to use the indexer. It's simpler, easier to read, and probably faster since you aren't creating an anonymous function.

提交回复
热议问题