CodeBlanks Logo Icon CodeBlanks

ChannelWriter

C# course · Expert · Lesson 32/47

Learn to write to a channel with ChannelWriter<T>.

ChannelWriter<T>

ChannelWriter<T> is the producer side of a channel. WriteAsync(item) writes asynchronously and waits when the channel is full. TryWrite(item) tries immediately, returning true on success or false when full or completed.

In a synchronous flow, TryWrite is handy for a quick non-blocking attempt. In async code, await WriteAsync flows more naturally.

TryWrite and TryComplete

TryWrite always returns true on an unbounded channel (unless completed). On a bounded channel it returns false when full; this is the synchronous way to detect backpressure.

TryComplete(exception) can close the channel with an error that propagates to the consumer. Writer.Complete() is the normal close.

Exercise Write three items with TryWrite

channel is an unbounded string channel. Write three items ("a", "b", "c") with channel.Writer.TryWrite and print the bool returned by each call with Console.WriteLine.

Show example solution
Call Console.WriteLine(channel.Writer.TryWrite("...")); three times.
Example solution:
using System;
using System.Threading.Channels;

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

Test yourself

  1. Match each write method

    WriteAsync
    Write asynchronously (await)
    TryWrite
    Try now, return bool
    WaitToWriteAsync
    Wait until space opens
  2. Which method writes asynchronously to a ChannelWriter?

    • Write
    • Send
    • WriteAsync
    • TryWrite
    Show answer

    WriteAsync — Correct. WriteAsync writes asynchronously.

  3. Complete the TryWrite call

    channel.Writer.____;
    Show answer
    channel.Writer.TryWrite("message");

All lessons in Expert