2

When working with a concurrent collection (for example ConcurrentDictionary) should I use TryAdd method, or just a plain old index assignment? I mean, do TryAdd method blocks when adding, so if another thread would try to remove the value it would have to wait until add is complete?

Marek M.
  • 3,799
  • 9
  • 43
  • 93

2 Answers2

2

Both the indexer's setter and Add call TryAdd internally.

public TValue this[TKey key]
{
  get { /*Irrelevant*/ }
  set
  {
    if ((object) key == null)
      throw new ArgumentNullException("key");
    TValue resultingValue;
    this.TryAddInternal(key, value, true, true, out resultingValue);
  }
}

Add method:

void IDictionary<TKey, TValue>.Add(TKey key, TValue value)
{
  if (!this.TryAdd(key, value))
    throw new ArgumentException(this.GetResource("ConcurrentDictionary_KeyAlreadyExisted"));
}
e_ne
  • 8,340
  • 32
  • 43
2

The prefix try has nothing to do with thread safety. It is just exception-free version of Add.

Hamlet Hakobyan
  • 32,965
  • 6
  • 52
  • 68
  • So if I want my code to be thread safe what should I do? Are concurrent collections thread safe "by default", and so I may as well just use index assignment? – Marek M. Jan 13 '13 at 14:41