Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C#

System.Collections.Concurrent.ConcurrentBag: practical reference

System.Collections.Concurrent.ConcurrentBag: practical reference: ConcurrentBag<T> is a thread-safe unordered collection optimized for threads that add and take their own local items.

Version: .NET API; verified on .NET 10.0.14

Syntax

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

ConcurrentBag is a thread-safe unordered collection optimized for threads that add and take their own local items.

Use it for work or object pools where ordering is irrelevant and producers often also consume.

Do not assume FIFO or which item TryTake returns; Count is only a transient observation during concurrent changes.

TryTake on an empty bag returns false, and enumeration observes a snapshot that ignores later modifications.

The complete program actually uses System.Collections.Concurrent.ConcurrentBag; its exact expected stdout is 3.

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

Result

3

The complete program actually uses `System.Collections.Concurrent.ConcurrentBag`; its exact expected stdout is `3`.

Sources