Why a Channel needs a CancellationToken if it has Complete method?

597 views Asked by At

I'm using System.Threading.Channel. The Channel.Reader.WaitToReadAsync accepts a CancellationToken. But, there is also Channel.Writer.TryComplete() or Channel.Writer.Complete() methods. So, why would I use a cancellation token to stop waiting if I just can call Complete which will stop the waiting?

1

There are 1 answers

0
Theodor Zoulias On

The ChannelReader<T>.WaitToReadAsync(CancellationToken) allows a consumer of the channel to stop consuming the channel, either temporarily or permanently, by using the optional cancellationToken parameter. For example a consumer might have to do some periodic work every minute, in which case it could use a timer-based CancellationTokenSource in order to cancel the wait, do the periodic work, and then continue consuming¹.

The ChannelWriter<T>.Complete prevents the producers of the channel from writing more messages, and when the channel is drained, it informs the consumers of the channel that no more messages are going to be available.

So these two APIs serve different purposes.

¹ Actually this pattern is currently problematic because of a memory leak in the implementation of the built-in Channels.