Runtime: Channels: Please include common use extensions.

Created on 4 May 2018  路  3Comments  路  Source: dotnet/runtime

In my use of channels recently I'm very commonly repeating a simple consumer pattern.
It would be good to have this in the code base so it got reviewed by the community and kept up to date.

Common Use Case Example (Simple)

var reader = _channel.Reader;
while (await reader.WaitToReadAsync().ConfigureAwait(false))
{
    while (reader.TryRead(out T item))
    {
        // Consume item.
    }
}

Ideas

I do not know the best way to include this as a proper set of extensions, but just a few examples:

public static async Task Consume(this ChannelReader<T> source, Action<T> consumer)
{
    while (await reader.WaitToReadAsync().ConfigureAwait(false))
    {
        while (reader.TryRead(out T item)) consumer(item);
    }
}
public static async Task Consume(this ChannelReader<T> source, Func<T, Task> consumer, CancellationToken token)
{
    while (await reader.WaitToReadAsync(token).ConfigureAwait(false))
    {
        await consumer(await ReadAsync(token));
    }
}

Most helpful comment

Right. We explicitly didn't add anything here yet as we intend to do so with support ala:
C# foreach await (var item in channel.Reader) { ... }

All 3 comments

This will get solved when the next version of c# adds support for async foreach.

Right. We explicitly didn't add anything here yet as we intend to do so with support ala:
C# foreach await (var item in channel.Reader) { ... }

mindblow

I see, so something similar to AsyncEnumerable will solve the 'next' and 'complete' problem.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

jkotas picture jkotas  路  3Comments

noahfalk picture noahfalk  路  3Comments

v0l picture v0l  路  3Comments

chunseoklee picture chunseoklee  路  3Comments

nalywa picture nalywa  路  3Comments