Is there a C# class like Queue that implements IAsyncEnumerable?(是否有像 Queue 这样实现 IAsyncEnumerable 的 C# 类?)
问题描述
Queue
和 ConcurrentQueue
都实现 IEnumerable
但不实现 IAsyncEnumerable
.NuGet 上是否有实现 IAsyncEnumerable
的标准类或类,这样,如果队列为空,则 MoveNextAsync
的结果直到将下一个内容添加到排队?
Both Queue
and ConcurrentQueue
implement IEnumerable
but not IAsyncEnumerable
. Is there a standard class or class available on NuGet which implements IAsyncEnumerable
such that, if the queue is empty, the result of MoveNextAsync
does not complete until something next is added to the queue?
推荐答案
如果您使用的是 .NET Core 平台,则至少有两个内置选项:
If you are using the .NET Core platform there are at least two built-in options:
System.Threading.Tasks.Dataflow.BufferBlock<T>
类,TPL 数据流 库.它没有原生实现IAsyncEnumerable<T>
,但它公开了可等待的OutputAvailableAsync()
方法,实现ToAsyncEnumerable
很简单扩展方法.
The
System.Threading.Tasks.Dataflow.BufferBlock<T>
class, part of the TPL Dataflow library. It doesn't implement theIAsyncEnumerable<T>
natively, but it exposes the awaitableOutputAvailableAsync()
method, doing it trivial to implement aToAsyncEnumerable
extension method.
System.Threading.Channels.Channel<T>
类,频道 库.它通过其公开 IAsyncEnumerable<T>
实现Reader.ReadAllAsync()
¹ 方法.
The System.Threading.Channels.Channel<T>
class, the core component of the Channels library. It exposes an IAsyncEnumerable<T>
implementation via its
Reader.ReadAllAsync()
¹ method.
通过安装 nuget 包(每个类不同),这两个类也可用于 .NET Framework.
Both classes are also available for .NET Framework, by installing a nuget package (different for each one).
BufferBlock
IAsyncEnumerable
实现:
public static async IAsyncEnumerable<T> ToAsyncEnumerable<T>(
this IReceivableSourceBlock<T> source,
[EnumeratorCancellation]CancellationToken cancellationToken = default)
{
while (await source.OutputAvailableAsync(cancellationToken).ConfigureAwait(false))
{
while (source.TryReceive(out T item))
{
yield return item;
cancellationToken.ThrowIfCancellationRequested();
}
}
await source.Completion.ConfigureAwait(false); // Propagate possible exception
}
¹(不适用于 .NET Framework,但易于在 类似方式)
¹ (not available for .NET Framework, but easy to implement in a similar way)
这篇关于是否有像 Queue 这样实现 IAsyncEnumerable 的 C# 类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:是否有像 Queue 这样实现 IAsyncEnumerable 的 C# 类?


基础教程推荐
- 是否可以在 asp classic 和 asp.net 之间共享会话状态 2022-01-01
- 错误“此流不支持搜索操作"在 C# 中 2022-01-01
- 将事件 TextChanged 分配给表单中的所有文本框 2022-01-01
- 全局 ASAX - 获取服务器名称 2022-01-01
- JSON.NET 中基于属性的类型解析 2022-01-01
- 从 VS 2017 .NET Core 项目的发布目录中排除文件 2022-01-01
- 首先创建代码,多对多,关联表中的附加字段 2022-01-01
- 在 VS2010 中的 Post Build 事件中将 bin 文件复制到物 2022-01-01
- 如何动态获取文本框中datagridview列的总和 2022-01-01
- 经典 Asp 中的 ResolveUrl/Url.Content 等效项 2022-01-01