C#

Concurrent collections in C#: safe operations and workflow boundaries

Nick Cosentino (Dev Leader)
C#

ConcurrentDictionary protects individual collection operations, not a multi-step workflow. The article separates which calls are genuinely atomic, why value factories can run more than once, and where a shared lock or an explicit invariant is still required.

Key points

  • TryAdd combines the existence check and the insert, so a preceding ContainsKey call adds nothing.
  • GetOrAdd and AddOrUpdate delegates run outside the dictionary's internal locks and may execute multiple times.
  • Irreversible side effects such as charging a card inside a value factory break exactly-once expectations.
  • TryUpdate writes only when the expected value still matches; the false result needs an explicit conflict policy.
  • Enumeration is safe during writes but is not a point-in-time snapshot; ToArray() gives a consistent copy.
  • A quota that combines Count, a limit check and TryAdd is not preserved without one shared lock.

Real-world use

  • A background job dispatcher where several workers must not claim the same task.
  • A per-tenant quota that caps the number of active jobs at a fixed limit.
  • A computed-value cache whose factory calls an external service and must stay idempotent.
  • Internal diagnostic views that iterate live state and tolerate a moving picture.

This summary was generated by the agent from the original post on Nick Cosentino (Dev Leader). The full text and all rights belong to its author and publisher. Go to original

Report this story

Is something wrong with the summary, or do you own this content? Your message comes straight to my inbox.

Type of message

Related stories

Feedback

Found a bug or have an idea? Your message lands straight in my inbox.

Type of message