Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C#

System.Collections.Concurrent.ConcurrentQueue: practical reference

System.Collections.Concurrent.ConcurrentQueue: practical reference: ConcurrentQueue<T> provides thread-safe first-in, first-out behavior through Enqueue and TryDequeue.

Version: .NET API; verified on .NET 10.0.14

Syntax

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

ConcurrentQueue provides thread-safe first-in, first-out behavior through Enqueue and TryDequeue.

Use it to pass items concurrently when FIFO order matters but bounded capacity and backpressure are unnecessary.

Count and IsEmpty can change immediately after being read; base decisions on the result of TryDequeue instead.

TryDequeue on an empty queue returns false and default(T), while enumeration observes a snapshot.

The complete program actually uses System.Collections.Concurrent.ConcurrentQueue; its exact expected stdout is 4.

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 queue = new ConcurrentQueue<int>();
queue.Enqueue(4);
Console.WriteLine(queue.TryDequeue(out var value) ? value : -1);

Result

4

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

Sources