This repo is a place for me to practice System.Threading.Channels.
These are key points for my understanding, not for understanding System.Threading.Channels in general.
We can use the nice properties given to us with IAsyncEnumerable<T> to create a foreach that waits on new data coming in. An example of this is seen in Basic.Run3() and used through the Workflows.cs file:
await foreach (string item in _channelReader.ReadAllAsync())
{
Console.WriteLine(item);
}The above seems to be preferred pattern because we can also write infinite loops. See Basic.cs for examples of loops.
The pattern here seems to be construct the object with a reader, writer, or both. This is seen in Workflows.cs, where each class gets given the reader that the previous object in the workflow writes to, and a writer to pass information to the next object in the workflow. The class that creates these workflow steps is the one that determines who gets which channel's reader and writer.
public class WorkflowStep1
{
private readonly ChannelReader<string> _channelReader;
private readonly ChannelWriter<string> _channelWriter;
public WorkflowStep1(ChannelReader<string> channelReader, ChannelWriter<string> channelWriter)
{
_channelReader = channelReader;
_channelWriter = channelWriter;
}
public async Task Run()
{
await foreach (string item in _channelReader.ReadAllAsync())
{
Console.WriteLine($"In {GetType().Name}, processing {item}");
await _channelWriter.WriteAsync($"{item}i");
}
_channelWriter.Complete();
}
}Completing a channel will break the control flow out of the ReadAllAsync() call and continue into the rest of the function. I used this in Workflows.cs to cascade completions down the workflow. Not sure if this is a good pattern, but it was neat that it worked.
- An Introduction to System.Threading.Channels via devblogs
- An Introduction to System.Threading.Channels via Steve Gordon
- Use System.IO.Pipelines and System.Threading.Channels APIs to Boost Performance
- C# Channels - Publish / Subscribe Workflows
- Async Expert course video
- Using Channels In C# .NET – Part 1 – Getting Started
- Example Producer/Consumer Patterns