Foreach Loop in C# (part 4)
Beginning with C# 8.0, you can use the
You can also use the
🔸 A type has the public parameterless
🔸 The return type of the
By default, stream elements are processed in the captured context. If you want to disable capturing of the context, use the TaskAsyncEnumerableExtensions.ConfigureAwait extension method. For more information about synchronization contexts and capturing the current context, see Consuming the Task-based asynchronous pattern. For more information about asynchronous streams, see the Asynchronous streams section of the What's new in C# 8.0 article.
💬 Support the channel and its mission to help programmers learn C#: https://www.patreon.com/csharp1001notes
Beginning with C# 8.0, you can use the
await foreach
statement to consume an asynchronous stream of data, that is, the collection type that implements the IAsyncEnumerable<T> interface. Each iteration of the loop may be suspended while the next element is retrieved asynchronously. The following example shows how to use the await foreach
statement:You can also use the
await foreach
statement with an instance of any type that satisfies the following conditions:🔸 A type has the public parameterless
GetAsyncEnumerator
method. That method can be a type's extension method.🔸 The return type of the
GetAsyncEnumerator
method has the public Current
property and the public parameterless MoveNextAsync
method whose return type is Task<bool>
, ValueTask<bool>
, or any other awaitable type whose awaiter's GetResult
method returns a bool
value.By default, stream elements are processed in the captured context. If you want to disable capturing of the context, use the TaskAsyncEnumerableExtensions.ConfigureAwait extension method. For more information about synchronization contexts and capturing the current context, see Consuming the Task-based asynchronous pattern. For more information about asynchronous streams, see the Asynchronous streams section of the What's new in C# 8.0 article.
💬 Support the channel and its mission to help programmers learn C#: https://www.patreon.com/csharp1001notes