CodeBlanks Logo Icon CodeBlanks

Bounded channel

C# course · Expert · Lesson 34/47

Learn backpressure and WaitToWriteAsync in bounded channels.

Bounded channel and backpressure

On a bounded channel, WriteAsync waits when full; this is backpressure. It slows the producer to the consumer's pace and prevents memory bloat.

WaitToWriteAsync() waits until writing is possible and returns a ValueTask<bool>. TryWrite returns false immediately without waiting; it is the synchronous way to detect backpressure.

BoundedChannelFullMode

BoundedChannelFullMode chooses the full behavior: Wait (default), DropOldest (drop the oldest), DropNewest (drop the newest), DropWrite (drop the write).

For example new BoundedChannelOptions(3) { FullMode = BoundedChannelFullMode.DropOldest } drops the oldest item when full. It fits log streams where losing old entries is tolerable.

Exercise Try TryWrite on a bounded channel

Create a bounded string channel with capacity 2. Write three items ("a", "b", "c") with channel.Writer.TryWrite and print the bool result of each call with Console.WriteLine. The third call returns False because the channel is full.

Show example solution
var channel = Channel.CreateBounded<string>(2); Then Console.WriteLine(channel.Writer.TryWrite("a")); Console.WriteLine(channel.Writer.TryWrite("b")); Console.WriteLine(channel.Writer.TryWrite("c"));
Example solution:
using System;
using System.Threading.Channels;

class Program
{
    static void Main()
    {
        var channel = Channel.CreateBounded<string>(2);
        Console.WriteLine(channel.Writer.TryWrite("a"));
        Console.WriteLine(channel.Writer.TryWrite("b"));
        Console.WriteLine(channel.Writer.TryWrite("c"));
    }
}

Test yourself

  1. What does WaitToWriteAsync return?

    • void
    • string
    • int
    • ValueTask<bool>
    Show answer

    ValueTask<bool> — Correct. WaitToWriteAsync returns ValueTask<bool>.

  2. Match each FullMode behavior

    Wait
    Waits when full
    DropOldest
    Drops the oldest
    DropWrite
    Silently drops the write
  3. Complete the WaitToWriteAsync condition

    if (await channel.Writer.____) { channel.Writer.TryWrite("x"); }
    Show answer
    if (await channel.Writer.WaitToWriteAsync()) { channel.Writer.TryWrite("x"); }

All lessons in Expert