Base di conoscenzaCentro esami
ITItaliano
Scegli la lingua13

CKTIS / C#

System.Collections.Concurrent.ConcurrentBag: riferimento pratico

System.Collections.Concurrent.ConcurrentBag: riferimento pratico: ConcurrentBag<T> è una raccolta non ordinata thread-safe, ottimizzata quando i thread aggiungono e prelevano i propri elementi locali.

Versione: .NET API; verified on .NET 10.0.14

Sintassi

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

ConcurrentBag è una raccolta non ordinata thread-safe, ottimizzata quando i thread aggiungono e prelevano i propri elementi locali.

Usala per pool di lavoro o oggetti in cui l’ordine è irrilevante e i produttori spesso consumano a loro volta.

Non presumere FIFO né quale elemento restituisca TryTake; Count è solo un’osservazione momentanea durante modifiche concorrenti.

TryTake su un bag vuoto restituisce false e l’enumerazione vede uno snapshot che ignora le modifiche successive.

Il programma completo usa realmente System.Collections.Concurrent.ConcurrentBag; lo stdout esatto atteso è 3.

Esempi

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

Risultato

3

Il programma completo usa realmente `System.Collections.Concurrent.ConcurrentBag`; lo stdout esatto atteso è `3`.

Fonti