是否可以在任何给定时间查看 C# 频道中的所有项目

Is it possible to view all items in a C# channel at any given time

我的 dotnet 6 应用程序需要后台队列服务。我按照 this Microsoft doc 创建了它的骨骼。

由于我的应用程序的性质,有可能将一个项目多次添加到我的队列中,为了提高效率,我想避免这种情况。

有什么方法可以在我添加之前检查频道中是否存在该id? 我能找到的只是 Channel.Reader.TryPeek() 方法,我认为它无法提供我需要的东西。

不,built-in Channel<T> 实现不提供此功能。您只能查看当前位于队列头部的项目。存储在 Channel<T> 中的所有其他项目都不可访问,直到它们到达头部并且可以被窥视或消耗。

也就是说,Channel<T> class is extensible. You could implement you own Channel<T>-derived class, and equip it with the functionality that you want. You can find an example . This is not a trivial undertaking though, especially if you are aiming at the memory-efficiency of the built-in implementations. These are based on the IValueTaskSource<T> 接口,用于在无法立即从通道添加或消费项目时最小化 await 操作的内存分配,生产者或消费者必须等待.