Concurrent Dictionary AddOrUpdate vs Index Add

前端 未结 4 453
走了就别回头了
走了就别回头了 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:59

    If I know that the 'key' exists, are these functionally equivalent?

    The way you're using it, yes. In fact, they're equivalent whether key exists or not.

    What are the reasons for choosing one over the other?

    AddOrUpdate accepts a function to be used to update the value. You're just using it to set the value directly, but it is designed to be used to update the value in a concurrent fashion based on the result of a function. For example:

    concurrentDictionary2.AddOrUpdate(key, value, (k, v) => v + value);  // adds value to the existing value
    

提交回复
热议问题