ConcurrentDictionary<T>, immutable collections
Use ConcurrentDictionary for thread-safe updates and learn simple immutable approaches: read-only views and copy-on-write.
ConcurrentDictionary<T>, immutable collections is a free C# Academy lesson on CoddyKit — lesson 2 of 3. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the C# Academy learning path, one of 3 lessons in the course, and your progress syncs across the web and the CoddyKit app.
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);
}
}
Race-free increment idea
AddOrUpdate avoids the classic read-modify-write race by updating atomically.
using System;
using System.Collections.Concurrent;
public class Program
{
static int Inc(int oldValue) { return oldValue + 1; }
public static void Main(string[] args)
{
ConcurrentDictionary<string, int> clicks = new ConcurrentDictionary<string, int>();
// Simulate multiple updates
for (int i = 0; i < 5; i++)
{
clicks.AddOrUpdate("home", 1, delegate(string k, int v) { return Inc(v); });
}
Console.WriteLine("home clicks = " + clicks["home"]); // 5 (starting at 1 then +4)
}
}
Read-only view (not immutable)
AsReadOnly returns a read-only view, not a truly immutable collection: changes to the source appear in the view.
using System;
using System.Collections.Generic;
public class Program
{
public static void Main(string[] args)
{
List<string> items = new List<string>(new string[] { "A", "B" });
var ro = items.AsReadOnly(); // ReadOnlyCollection<string>
foreach (string s in ro) Console.WriteLine(s); // A, B
// ro.Add("C"); // not available: read-only view has no Add
// But changing the source list reflects in the view:
items.Add("C");
Console.WriteLine("After source change:");
foreach (string s in ro) Console.WriteLine(s); // A, B, C
}
}
Copy-on-write snapshot
Copy-on-write: return a new list for changes. Callers who keep the old list see a stable snapshot.
using System;
using System.Collections.Generic;
public class Program
{
static List<int> AddWithoutTouchingOriginal(List<int> original, int item)
{
// create a copy and modify the copy
List<int> copy = new List<int>(original);
copy.Add(item);
return copy;
}
public static void Main(string[] args)
{
List<int> a = new List<int>(new int[] { 1, 2 });
List<int> b = AddWithoutTouchingOriginal(a, 3);
Console.WriteLine("Original:");
foreach (int x in a) Console.WriteLine(x); // 1,2
Console.WriteLine("Copy:");
foreach (int x in b) Console.WriteLine(x); // 1,2,3
}
}
Tips & trade-offs
Tips:
- Use ConcurrentDictionary for shared counters/caches.
- AsReadOnly prevents accidental mutation by consumers.
- For a stable view, copy the list before modifying.
- True immutable collections live in System.Collections.Immutable (package); not used here to keep code standalone.
Thread-safe dictionary pick
Recap
Recap: Use ConcurrentDictionary for concurrent updates. Expose read-only views to callers, and use copy-on-write when you need stable snapshots.
Frequently asked questions
Is the “ConcurrentDictionary<T>, immutable collections” lesson free?
Yes — the full text of “ConcurrentDictionary<T>, immutable collections” is free to read here on the web, and the C# Academy course includes 3 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the C# Academy course, upgrade to CoddyKit PRO.
What will I learn in “ConcurrentDictionary<T>, immutable collections”?
Use ConcurrentDictionary for thread-safe updates and learn simple immutable approaches: read-only views and copy-on-write. You practise C# Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start C# Academy?
No prior experience is required. C# Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 2 of 3, so you can start here or from the beginning and move at your own pace.
How long does the “ConcurrentDictionary<T>, immutable collections” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this C# Academy lesson?
Yes. Every C# Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- HashSet , SortedSet , Queue , Stack
- ConcurrentDictionary , immutable collections
- Equality & hashing (value vs reference)