CKTIS / C#
BoundedChannelOptions et BoundedChannelFullMode.Wait
Fixez la capacité du tampon : quand le canal est plein, `TryWrite` renvoie immédiatement `false`, tandis que `WriteAsync` attend une place de façon asynchrone.
Version : C# 12 and .NET 8; later runtimes may add compatible features
Syntaxe
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);En C# 12 et .NET 8, transmettez BoundedChannelOptions, du namespace System.Threading.Channels, à Channel.CreateBounded<T>(options). Une Capacity positive limite le nombre d’éléments dans le tampon, pas ceux que les consommateurs traitent déjà ni le nombre d’écritures en attente. La surcharge plus simple Channel.CreateBounded<T>(capacity) utilise aussi Wait.
FullMode détermine le comportement d’une écriture quand le tampon est plein. Le mode par défaut BoundedChannelFullMode.Wait ne supprime aucun élément pour gérer la saturation. TryWrite(item) renvoie true si l’écriture réussit, ou immédiatement false si le canal est plein ou si les écritures ont été clôturées. Un résultat false ne laisse aucune écriture en attente.
WriteAsync(item, cancellationToken) renvoie un ValueTask : l’écriture peut se terminer immédiatement, mais si le tampon est plein, elle attend une place sans bloquer de thread. Utilisez await avant de produire l’élément suivant pour qu’un consommateur lent puisse ralentir le producteur (contre-pression). L’annulation peut interrompre une écriture en attente avec OperationCanceledException, et la clôture normale des écritures avec ChannelClosedException. Une écriture réussie signifie que l’élément a été accepté, pas traité.
WaitToWriteAsync signale qu’une écriture est possible sans réserver de place. Avec plusieurs producteurs, un autre peut prendre la place ; si TryWrite échoue, attendez de nouveau si l’écriture reste possible. Après une clôture normale avec Complete(), le consommateur peut encore vider le tampon.
Exemples
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}");
}Résultat
TryWrite(99): False WriteAsync(2) completed: False Read: 1 Read: 2
`1` remplit le tampon. La tentative d’écriture de `99` échoue et l’écriture de `2` reste en attente. Lire `1` libère une place, l’écriture de `2` se termine et `ReadAllAsync()` lit `2` après `Complete()`.
Leçons associées
- C# · Leçon 46 · Avancé · Version : 3
Sources
- 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