Another point:
// This might fail if another thread is adding with key value of 1. cd.TryAdd(1, "one");
This comment is incorrect and may suffer from the same misconception about what it means to "try." This is not about a parallel attempt to add, whether the value has already been added using key 1 .
Consider the standard Dictionary<TKey,TValue> . The equivalent code would be:
if (!d.Contains(1)) d.Add(1, "one");
This requires two operations. There is no way to create such an API to be thread safe, since cd can have a value with a key of 1 added between the Contains and Add calls, which then leads to the Add metallocation.
Parallel collections have APIs that logically combine these test pairs into single atomic operations in one API.
Drew Noakes Oct 07 '17 at 20:09 on 2017-10-07 20:09
source share