CKTIS / C#
BoundedChannelOptions e BoundedChannelFullMode.Wait
Imposta il limite del buffer e scopri perché, quando il canale è pieno, `TryWrite` restituisce subito `false` mentre `WriteAsync` attende spazio in modo asincrono.
Versione: C# 12 and .NET 8; later runtimes may add compatible features
Sintassi
using System.Threading.Channels;
var options = new BoundedChannelOptions(capacity: 2)
{
FullMode = BoundedChannelFullMode.Wait
};
Channel<int> channel = Channel.CreateBounded<int>(options);
bool written = channel.Writer.TryWrite(1);
await channel.Writer.WriteAsync(2);In C# 12 e .NET 8, passa BoundedChannelOptions dello spazio dei nomi System.Threading.Channels a Channel.CreateBounded<T>(options). Una Capacity positiva limita il numero di elementi nel buffer, non quelli che i consumatori stanno già elaborando né le scritture in sospeso. Anche l’overload più semplice Channel.CreateBounded<T>(capacity) usa Wait.
FullMode stabilisce cosa succede quando si scrive con il buffer pieno. La modalità predefinita BoundedChannelFullMode.Wait non scarta elementi per gestire la saturazione. TryWrite(item) restituisce true se la scrittura riesce, oppure subito false se il canale è pieno o se le scritture sono state chiuse. Un risultato false non lascia scritture in sospeso.
WriteAsync(item, cancellationToken) restituisce un ValueTask: può completarsi subito, ma con il buffer pieno attende spazio senza bloccare un thread. Usa await prima di produrre l’elemento successivo, così un consumatore lento può rallentare il produttore (backpressure). L’annullamento può interrompere una scrittura in sospeso con OperationCanceledException, la chiusura normale delle scritture con ChannelClosedException. Il successo indica che l’elemento è stato accettato, non elaborato.
WaitToWriteAsync segnala la possibilità di scrivere, ma non riserva un posto. Se ci sono più produttori, un altro può occuparlo; se TryWrite fallisce, attendi di nuovo finché è ancora possibile scrivere. Dopo la chiusura normale con Complete(), il consumatore può ancora leggere gli elementi rimasti nel buffer.
Esempi
using System;
using System.Threading.Channels;
var channel = Channel.CreateBounded<int>(new BoundedChannelOptions(capacity: 1)
{
FullMode = BoundedChannelFullMode.Wait
});
await channel.Writer.WriteAsync(1);
Console.WriteLine($"TryWrite(99): {channel.Writer.TryWrite(99)}");
var pending = channel.Writer.WriteAsync(2);
Console.WriteLine($"WriteAsync(2) completed: {pending.IsCompleted}");
Console.WriteLine($"Read: {await channel.Reader.ReadAsync()}");
await pending;
channel.Writer.Complete();
await foreach (var item in channel.Reader.ReadAllAsync())
{
Console.WriteLine($"Read: {item}");
}Risultato
TryWrite(99): False WriteAsync(2) completed: False Read: 1 Read: 2
`1` riempie il buffer. Il tentativo di scrivere `99` fallisce e la scrittura di `2` resta in sospeso. Leggere `1` libera spazio, la scrittura di `2` si completa e `ReadAllAsync()` legge `2` dopo `Complete()`.
Lezioni correlate
- C# · Lezione 46 · Avanzato · Versione: 3
Fonti
- Channels - .NET
- BoundedChannelOptions Class
- BoundedChannelFullMode Enum
- Channel.CreateBounded Method
- ChannelWriter<T>.TryWrite(T) Method
- ChannelWriter<T>.WriteAsync(T, CancellationToken) Method
- ChannelWriter<T>.WaitToWriteAsync(CancellationToken) Method
- ChannelReader<T>.ReadAllAsync(CancellationToken) Method