Codectionary / Developer documentation / C#

ConcurrentDictionary Updates

ConcurrentDictionary supports concurrent access and atomic key updates. AddOrUpdate replaces unsafe separate read/write operations, but its delegates may be invoked more than once. Use a .NET 8+ console project; replace Program.cs with this C# example.

Read the syntax

ConcurrentDictionary supports concurrent access and atomic key updates. AddOrUpdate replaces unsafe separate read/write operations, but its delegates may be invoked more than once. Use a .NET 8+ console project; replace Program.cs with this C# example.

Parallel.For waits for its iterations to complete. Every successful update increments the stored value despite competing threads.

Syntax

dictionary.AddOrUpdate(key, initialValue, (key, old) => nextValue)

Examples

ConcurrentDictionary Updates

Use a .NET 8+ console project; replace Program.cs with this C# example.

using System;
using System.Collections.Concurrent;
using System.Threading.Tasks;
var counts = new ConcurrentDictionary<string, int>();
Parallel.For(0, 1000, _ => counts.AddOrUpdate("hits", 1, (key, old) => old + 1));
Console.WriteLine(counts["hits"]);
  1. Expected output: 1000
  2. Parallel.For waits for its iterations to complete. Every successful update increments the stored value despite competing threads.
  3. Keep update factories free of externally visible side effects because they can be retried.

Best practices

  • Keep update factories free of externally visible side effects because they can be retried.
  • Use additional coordination when an invariant spans multiple keys.

Runtime & versions

.NET runtime. Feature availability depends on the language and runtime version used by your project; consult the official reference below.

C# language reference

Specifications & further reading