ConcurrentDictionary Pitfall - Are delegates factories from GetOrAdd and AddOrUpdate synchronized?

前端 未结 2 1320
星月不相逢
星月不相逢 2020-12-02 17:02

The documentation of ConcurrentDictionary doesn\'t explicit state, so I guess we cannot expect that delegates valueFactory and u

2条回答
  •  伪装坚强ぢ
    2020-12-02 17:49

    Not only are these delegates not synchronized, but they are not even guaranteed to happen only once. They can, in fact, be executed multiple times per call to AddOrUpdate.

    For example, the algorithm for AddOrUpdate looks something like this.

    TValue value;
    do
    {
      if (!TryGetValue(...))
      {
        value = addValueFactory(key);
        if (!TryAddInternal(...))
        {
          continue;
        }
        return value;
      }
      value = updateValueFactory(key);
    } 
    while (!TryUpdate(...))
    return value;
    

    Note two things here.

    • There is no effort to synchronize execution of the delegates.
    • The delegates may get executed more than once since they are invoked inside the loop.

    So you need to make sure you do two things.

    • Provide your own synchronization for the delegates.
    • Make sure your delegates do not have any side effects that depend on the number of times they are executed.

提交回复
热议问题