[英]Whats the difference between IAsyncEnumerable<T> vs IEnumerable<Task<T>>?
The new C# 8.0 and dotnet core 3 has this new feature of AsyncStreams ( IAsyncEnumerable<T>
).新的 C# 8.0 和 dotnet core 3 具有 AsyncStreams (
IAsyncEnumerable<T>
) 的这一新功能。 My understanding it that it provides a way to asynchronously process items in a stream.我的理解是它提供了一种异步处理流中项目的方法。 But would I not be able to do that with
IEnumerable<Task<T>>
?但是我不能用
IEnumerable<Task<T>>
做到这一点吗?
what's the difference between these two approaches?这两种方法有什么区别?
Both Task<IEnumerable<T>>
and IAsyncEnumerable
are used to enumerate through data or go through a list of data. Task<IEnumerable<T>>
和IAsyncEnumerable
都用于枚举数据或遍历数据列表。 Yet there is a huge difference.然而还是有很大的不同。
Task<IEnumerable<T>>
provides records once the data in collection is ready to send to the caller.一旦集合中的数据准备好发送给调用者,
Task<IEnumerable<T>>
提供记录。
Whereas, IAsyncEnumerable
provides records as they are ready, which mean it will send you record as its available rather than waiting for the whole collection to be filled up.而
IAsyncEnumerable
在记录准备好时提供记录,这意味着它会将记录作为可用记录发送给您,而不是等待整个集合被填满。 It provides you to iterate a collection asynchronously using the yield keyword which was not possible until C# 8.0.它使您可以使用 yield 关键字异步迭代集合,这在 C# 8.0 之前是不可能的。
It's important to understand what thread is safe and what is not safe when working with async enumerables.在使用异步枚举时,了解哪些线程是安全的,哪些是不安全的,这一点很重要。
With a return type of IEnumerable<Task> you would return a blocking enumerator though the individual results are non-blocking.使用 IEnumerable<Task> 返回类型,您将返回阻塞枚举器,尽管单个结果是非阻塞的。
With IAsyncEnumerable the enumerator itself is non-blocking, providing more flexibility for the source of the enumerable to go async.使用 IAsyncEnumerable 枚举器本身是非阻塞的,为枚举源的异步提供更大的灵活性。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.