.NET Channels

This post is based upon a Channel9 video with Stephen Toub, I recommend you go and watch it (see references) if you’re interested in threadsafe producer/consumer mechanisms.

This is the namespace you want to be looking at

using System.Threading.Channels;

There are two types of channel, bounded and unbounded.

Bounded channels have a fixed size. In this example the queue within the channel will only allow a maximum of 10 items, meaning if we try to write more than the 10 items, the write method would block until an item is removed/read from the queue

var c = Channel.CreateBounded<int>(10);

So from this, we can tell that unbounded means the queue within the channel in unlimited in size. We create an unbounded channel like this

var c = Channel.CreateUnbounded<int>();

When we want to add items to the channel we use code such as the following, obviously if the queue has reached a limit (bounded) then this will block

c.Writer.TryWrite(123);

To read a value from the channel (if one exists) we use

await c.Reader.ReadAsync()

References

Working with Channels in .NET
An Introduction to System.Threading.Channels