Search code examples
c#system.threading.channels

How to make count available on .NET Channel


I have an UnboundedChannel single reader\multiple writers and I want to be able to use Count property, but since CanCount property is always false Count is throwing an exception. What should i do to make it work, i can't find any restrictions enlisted in docs.


Solution

  • When the UnboundedChannelOptions.SingleReader property is set to true on creation, the UnboundedChannel implementation is SingleConsumerUnboundedChannel. Based on the source, the Reader object used by this class extends ChannelReader without explicitly setting CanCount, which is set to false by ChannelReader by default.

    Unfortunately all these classes are sealed so you can't just extend them and implement Count yourself. Leaving the SingleReader option as false will use an UnboundedChannelReader implementation that does set CanCount to true and implements a Count method. If you just need to check whether there are more elements in the queue, you could also use TryPeek instead.