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

CKTIS / C#

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

System.Collections.Concurrent.ConcurrentBag: referência prática: ConcurrentBag<T> é uma coleção não ordenada segura entre threads, otimizada para threads que adicionam e retiram os próprios itens locais.

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

Sintaxe

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

ConcurrentBag é uma coleção não ordenada segura entre threads, otimizada para threads que adicionam e retiram os próprios itens locais.

Usa-a em pools de trabalho ou objetos onde a ordem não interessa e os produtores também costumam consumir.

Não pressuponhas FIFO nem qual elemento TryTake devolve; Count é apenas uma observação transitória durante alterações concorrentes.

TryTake devolve false num bag vazio e a enumeração observa um snapshot que ignora alterações posteriores.

O programa completo usa realmente System.Collections.Concurrent.ConcurrentBag; o stdout exato esperado é 3.

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 bag = new ConcurrentBag<int>();
bag.Add(3);
Console.WriteLine(bag.TryTake(out var value) ? value : -1);

Resultado

3

O programa completo usa realmente `System.Collections.Concurrent.ConcurrentBag`; o stdout exato esperado é `3`.

Fontes