Base de conhecimentoCentro de Exames
PT · PTPortuguês (Portugal)
Escolher idioma13

CKTIS / C#

System.Collections.Concurrent.ConcurrentDictionary: referência prática

System.Collections.Concurrent.ConcurrentDictionary: referência prática: ConcurrentDictionary<TKey,TValue> permite leituras concorrentes e operações atómicas sobre entradas individuais de chave e valor.

Versão: .NET API; verified on .NET 10.0.14

Sintaxe

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

ConcurrentDictionary<TKey,TValue> permite leituras concorrentes e operações atómicas sobre entradas individuais de chave e valor.

Usa AddOrUpdate, GetOrAdd e TryUpdate em mapas partilhados que têm de mudar em segurança entre threads.

As fábricas de valores podem executar-se mais do que uma vez fora dos bloqueios internos; evita efeitos não repetíveis.

Um método atómico não torna atómica uma sequência de métodos e uma chave null não é permitida.

O programa completo usa realmente System.Collections.Concurrent.ConcurrentDictionary; o stdout exato esperado é 1\n2.

Exemplos

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));

Resultado

1
2

O programa completo usa realmente `System.Collections.Concurrent.ConcurrentDictionary`; o stdout exato esperado é `1\n2`.

Fontes