0Pricing
C# Academy · Lesson

ConcurrentDictionary<T>, immutable collections

Use ConcurrentDictionary for thread-safe updates and learn simple immutable approaches: read-only views and copy-on-write.

Thread-safety & immutability basics

Today:

  • ConcurrentDictionary<TKey,TValue>: safe updates from multiple threads
  • Read-only views vs true immutability
  • Copy-on-write idea for simple safety

Atomic ops: GetOrAdd/AddOrUpdate

Use GetOrAdd and AddOrUpdate for atomic operations; TryGetValue to read safely.

using System;
using System.Collections.Concurrent;

public class Program
{
  public static void Main(string[] args)
  {
    ConcurrentDictionary<string, int> counts = new ConcurrentDictionary<string, int>();

    // Add if missing
    int a = counts.GetOrAdd("apple", 0); // 0
    // Increment safely
    int newVal = counts.AddOrUpdate("apple", 1, (key, oldValue) => oldValue + 1);

    Console.WriteLine("apple was " + a + ", now " + newVal);

    int value;
    bool ok = counts.TryGetValue("apple", out value);
    Console.WriteLine("Has apple? " + ok + " -> " + value);
  }
}

All lessons in this course

  1. HashSet , SortedSet , Queue , Stack
  2. ConcurrentDictionary , immutable collections
  3. Equality & hashing (value vs reference)
← Back to C# Academy