Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C#

System.Threading.Channels.ChannelReader: practical reference

System.Threading.Channels.ChannelReader: practical reference: ChannelReader<T> reads elements asynchronously and signals channel completion.

Version: .NET API; verified against .NET 10 reference surface

Syntax

System.Threading.Channels.ChannelReader /* select a documented member or constructor */

ChannelReader reads elements asynchronously and signals channel completion.

Use ReadAllAsync or a WaitToReadAsync/TryRead loop for an efficient consumer.

A true result from WaitToReadAsync does not guarantee an element when several readers compete.

ReadAsync on a completed empty channel throws ChannelClosedException.

The complete program actually uses System.Threading.Channels.ChannelReader; its exact expected stdout is 6.

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 channel = Channel.CreateUnbounded<int>(); channel.Writer.TryWrite(6);
ChannelReader<int> reader = channel.Reader;
Console.WriteLine(reader.TryRead(out var value) ? value : -1);

Result

6

The complete program actually uses `System.Threading.Channels.ChannelReader`; its exact expected stdout is `6`.

Sources