简体   繁体   中英

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> ). 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>> ?

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. Yet there is a huge difference. Task<IEnumerable<T>> provides records once the data in collection is ready to send to the caller.

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. It provides you to iterate a collection asynchronously using the yield keyword which was not possible until 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.

With IAsyncEnumerable the enumerator itself is non-blocking, providing more flexibility for the source of the enumerable to go async.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM