如何获取Channel<T>中的元素个数?

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

我正在规划订阅者和发布者系统,我打算在其中使用频道。我想记录我使用的每个通道中的元素数量,以便我可以根据系统中的瓶颈调整 publishers/subs 的数量。

我开始将 ChannelChannelReaderChannelWriter 包装到我自己的 类 中以计算写入和读取的次数,但这感觉像是 hack。有没有更好的方法?

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,将在 .NET Core 5.0(预计 11 月发布)中添加。