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

Theodor Zoulias
- 34,835
- 7
- 69
- 104

theateist
- 13,879
- 17
- 69
- 109
1 Answers
1
The ChannelReader<T>.WaitToReadAsync
allows a consumer of the channel to stop consuming the channel, either temporarily or permanently. 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.

Theodor Zoulias
- 34,835
- 7
- 69
- 104