Search code examples
c#.net-corechannelsystem.threading.channels

How to get the number of elements in a Channel<T>?


I am planning a subscribers and publishers system where I plan to use Channels. I would like to log the number of elements in each Channel I use so I can adjust the number of publishers/subs based on the bottlenecks in my system.

I started to wrap Channel, ChannelReader and ChannelWriter into my own classes to count the number of writes and reads but this feels like a hack. Is there a better way?


Solution

  • Use the source, Luke. The source tells you that (a) there is no public API to do that, (b) you can use reflection to get the value of the private property ItemsCountForDebugger on both bounded and unbounded channels, and (c) this is safe despite no locking in the getter. Of course this is a hack. Whether the reflection hack is better than wrapper class hack is a question of taste. Public API to get the approximate number of elements in a Channel<T> was requested back in 2018, and will be added in .NET Core 5.0 (slated for release in November).

    UPDATE: in net5.0 and later, ChannelReader has a Count property. It returns the item count for the System.Threading.Channels implementations of a bounded channel and an unbounded channel with multiple readers, but in the implementation of a single-consumer unbounded channel this property throws an exception. My old comment still applies in this case.