CodeBlanks Logo Icon CodeBlanks

Channel completion

C# course · Expert · Lesson 35/47

Learn to close a channel with Channel.Writer.Complete and Completion.

Channel completion

Writer.Complete() signals that no more items will be written. After the consumer drains the remaining items, ReadAllAsync ends gracefully.

Reader.Completion is a Task that completes when the channel is fully done. A waiting consumer can end with it. To close with an error use Writer.TryComplete(exception).

Graceful close

After the producer calls Writer.Complete(), the await foreach (var item in channel.Reader.ReadAllAsync()) loop drains the remaining items and then ends. This guarantees no data loss when closing the channel.

On the consumer side you can await channel.Reader.Completion to wait until the channel is fully done; it is especially useful when synchronizing several channels.

Exercise Close the stream with Complete

channel is an unbounded string channel. Write three items ("a", "b", "c") with await channel.Writer.WriteAsync. Then call channel.Writer.Complete(). Finally print all items with await foreach (var item in channel.Reader.ReadAllAsync()). Make Main async Task.

Show example solution
Call await channel.Writer.WriteAsync(...) three times, channel.Writer.Complete(); then await foreach (var item in channel.Reader.ReadAllAsync()) Console.WriteLine(item);
Example solution:
using System;
using System.Threading.Channels;
using System.Threading.Tasks;

class Program
{
    static async Task Main()
    {
        var channel = Channel.CreateUnbounded<string>();
        await channel.Writer.WriteAsync("a");
        await channel.Writer.WriteAsync("b");
        await channel.Writer.WriteAsync("c");
        channel.Writer.Complete();
        await foreach (var item in channel.Reader.ReadAllAsync())
        {
            Console.WriteLine(item);
        }
    }
}

Test yourself

  1. Match each completion method

    Writer.Complete()
    End writing
    Reader.Completion
    Channel's completion Task
    TryComplete(exception)
    Close with an error
  2. Complete the Complete call

    channel.Writer.____;
    Show answer
    channel.Writer.Complete();
  3. Which method signals that no more items will be written?

    • Writer.Complete()
    • Writer.Close()
    • Writer.Finish()
    • Reader.Complete()
    Show answer

    Writer.Complete() — Correct. Writer.Complete() ends writing.

All lessons in Expert