是否有像Queue这样的C#类实现IAsyncEnumerable? [英] Is there a C# class like Queue that implements IAsyncEnumerable?

查看:128
本文介绍了是否有像Queue这样的C#类实现IAsyncEnumerable?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

QueueConcurrentQueue都实现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:

  1. System.Threading.Tasks.Dataflow.BufferBlock<T> 类,是 TPL数据流的一部分图书馆.它不是本机实现IAsyncEnumerable<T>,而是公开了可等待的OutputAvailableAsync()方法,这对于实现ToAsyncEnumerable扩展方法来说是微不足道的.

  1. The System.Threading.Tasks.Dataflow.BufferBlock<T> class, part of the TPL Dataflow library. It doesn't implement the IAsyncEnumerable<T> natively, but it exposes the awaitable OutputAvailableAsync() method, doing it trivial to implement a ToAsyncEnumerable extension method.

System.Threading.Channels.Channel<T> 类,它是 Channels 库的核心组件.它通过其公开一个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<T>IAsyncEnumerable<T>实现:

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;
        }
    }
    await source.Completion.ConfigureAwait(false); // Propagate possible exception
}

¹(不适用于.NET Framework,但易于在

¹ (not available for .NET Framework, but easy to implement in a similar way)

这篇关于是否有像Queue这样的C#类实现IAsyncEnumerable?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆