Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C#

System.Collections.Concurrent.ConcurrentDictionary: practical reference

System.Collections.Concurrent.ConcurrentDictionary: practical reference: ConcurrentDictionary<TKey,TValue> supports concurrent reads and atomic operations on individual key-value entries.

Version: .NET API; verified on .NET 10.0.14

Syntax

System.Collections.Concurrent.ConcurrentDictionary /* select a documented member or constructor */

ConcurrentDictionary<TKey,TValue> supports concurrent reads and atomic operations on individual key-value entries.

Use AddOrUpdate, GetOrAdd, and TryUpdate for shared maps that must change safely across threads.

Value factories may execute more than once outside internal locks, so they must not perform non-repeatable side effects.

One atomic method does not make a sequence of methods atomic, and a null key is not permitted.

The complete program actually uses System.Collections.Concurrent.ConcurrentDictionary; its exact expected stdout is 1\n2.

Examples

using System;
using System.Buffers;
using System.Collections.Concurrent;
using System.Collections.Frozen;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Text;
using System.Text.Json;
using System.Text.Json.Nodes;
using System.Text.Json.Serialization;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Channels;
using System.Threading.Tasks;
using Number = System.Int32;

var map = new ConcurrentDictionary<string, int>();
Console.WriteLine(map.AddOrUpdate("x", 1, (_, old) => old + 1));
Console.WriteLine(map.AddOrUpdate("x", 1, (_, old) => old + 1));

Result

1
2

The complete program actually uses `System.Collections.Concurrent.ConcurrentDictionary`; its exact expected stdout is `1\n2`.

Sources