With access to every item being asynchronous, the consuming code could decide to access the items out of order or even skip some of the items. This would require the following code to consume:Īlthough it might not seem so at first glance, this makes it even more difficult to wrap paginated calls than the previous approach. This is still beneficial in scenarios where all the data can be retrieved in one batch, e.g., with a single API call.īut as soon as that API implements pagination to restrict the maximum number of items that can be retrieved in one call, the asynchronous method above will start to have a negative impact on the performance because the iteration will still start only after all the data is retrieved.Įven the data from the first API call will only be accessible after all the API calls are made.įigure 1: With Task>, all items are loaded before the iteration startsĪlternatively, one could access individual items asynchronous by using the following method signature: Such a method would then be consumed with following code:Īlthough the code above is asynchronous, there are limitations to it.įor this to work, all of the items have to be ready before the iteration can start because only the GetItems() method result is retrieved asynchronously, while the iteration through it happens synchronously. NET, IEnumerable is the base interface for representing collections of items.Īn IEnumerable could be accessed asynchronously even before C# v8 by changing the signature of the method from: However, there are use cases in which async streams can make your code simpler and easier to follow by allowing you to do things that were not (easily) possible before.įor example, whenever you are dealing with a collection of items that can be slow to access or generate, you can use async streams to consume them asynchronously one-by-one as they become available. This might be the reason why async streams have attracted less attention. When compared to Async Streams, there are many other features in C# 8 that are more frequently used (like improved pattern matching, for example) or have a much higher impact on the language (nullable reference types). If you want to refresh your memory, you can read about them in my DNC Magazine article New C# 8 Features in Visual Studio 2019. Async streams were one of the many new language features introduced in C# 8.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |