The problem
public async TaskTask<IEnumerable<User>>Represents an asynchronous operation that can return a value.<Task<IEnumerable<User>>Represents an asynchronous operation that can return a value.IEnumerableIEnumerable<User>Exposes the enumerator, which supports a simple iteration over a collection of a specified type.<IEnumerable<User>Exposes the enumerator, which supports a simple iteration over a collection of a specified type.UserUser>IEnumerable<User>Exposes the enumerator, which supports a simple iteration over a collection of a specified type.>Task<IEnumerable<User>>Represents an asynchronous operation that can return a value. GetUsersTask<IEnumerable<User>> Example.GetUsers()(){ varList<User>Represents a strongly typed list of objects that can be accessed by index. Provides methods to search, sort, and manipulate lists. allResultsList<User>? allResults = new ListList<User>Represents a strongly typed list of objects that can be accessed by index. Provides methods to search, sort, and manipulate lists.<List<User>Represents a strongly typed list of objects that can be accessed by index. Provides methods to search, sort, and manipulate lists.UserUser>List<User>Represents a strongly typed list of objects that can be accessed by index. Provides methods to search, sort, and manipulate lists.(); varstringRepresents text as a sequence of UTF-16 code units. nextUrlstring? nextUrl = "https://account.zendesk.com/api/v2/users.json"; while (nextUrlstring? nextUrl !=Task<IEnumerable<User>> Example.GetUsers() null) { varTask<IEnumerable<User>> Example.GetUsers() page = await _clientHttpClient Example._client.GetAsyncTask<HttpResponseMessage> HttpClient.GetAsync(string? requestUri)Send a GET request to the specified Uri as an asynchronous operation.ParametersrequestUri — The Uri the request is sent to.ReturnsThe task object representing the asynchronous operation.ExceptionsInvalidOperationException — The requestUri must be an absolute URI or BaseAddress must be set.HttpRequestException — The request failed due to an underlying issue such as network connectivity, DNS failure, server certificate validation or timeout.TaskCanceledException — .NET Core and .NET 5 and later only: The request failed due to timeout.UriFormatException — The provided request URI is not valid relative or absolute URI.(nextUrlstring? nextUrl) .Content.ReadAsAsync<UsersListResponseUsersListResponse>(); allResultsList<User>? allResults.AddRangevoid List<User>.AddRange(IEnumerable<User> collection)Adds the elements of the specified collection to the end of the List`1.Parameterscollection — The collection whose elements should be added to the end of the List`1. The collection itself cannot be , but it can contain elements that are , if type T is a reference type.ExceptionsArgumentNullException — collection is .(page.UsersTask<IEnumerable<User>> Example.GetUsers()); nextUrlstring? nextUrl = page.NextPageTask<IEnumerable<User>> Example.GetUsers(); // eg "https://account.zendesk.com/api/v2/users.json?page=2" } return allResultsList<User>? allResults;}Take a look at the above code, you may have run into this familiar issue yourself. We’d like to represent the pageable results of this HTTP API in our types, while still be asynchronous.
Traditionally there would be 4 ways to approach this;
- Block on the async code with
.Result/.GetAwaiter().GetResult()or.Wait(). This is not a good idea. - The above approach of awaiting each asynchronous task, but doing it all eagerly and returning the complete results in a materialised collection. This defeats the purpose of this paging API, and more generally we lose the laziness of the problem we are trying to model.
- We flip the return type to
IEnumerable<Task<User>>. This would require that we trust any consumers of this code to await the result of each task after every enumeration. There are ways to enforce this at runtime, and throw an exception if it’s not consumed correctly, however this ultimately is a misleading type, and the shape of the type doesn’t communicate it’s hidden constraints. - We don’t try returning a single type such as
Task<IEnumerable<T>>and we model it ourselves. This can be a good idea, but we lose the benefits of having a familiar type to work with.
Well it’s about time we adopted a new type and end this madness. That’s what IAsyncEnumerable<T> is for.
About Ix.Async
Currently IAsyncEnumerable<T> is a concept which exists in a few places, with no singular definition. The version I will be using today lives in the Reactive Extensions repo, in a fork that is based off of the latest C# 8.0 proposal.
Reactive Extensions (Rx) is the home of Observable implementation and extensions, it is also home to a sibling project named Interactive Extensions (Ix for short). Rx has lots of extensions and tools for composing pushed based sequences, and Ix is very similar but for pull based sequences (IEnumerable<T>). The part I am interested in for this post is the async part, which I’ll be referring to as Ix.Async, this is shipped in it’s own nuget package, and I will generally be referring to the IAsyncEnumerable<T> definition that lives here (although this will map trivially to other implementations).
In the near future, C# 8.0 will introduce Async Streams (I prefer the term Sequence, as Stream is already a different .NET concept) as a language feature, and there will be a new definition of IAsyncEnumerable<T> it will work with, but that doesn’t stop us using Ix.Async today, either using the current definition which slightly differs from the C# 8.0 proposal, or building the fork with the latest definition in.
Definition
public interface IAsyncEnumerableIAsyncEnumerable<T><IAsyncEnumerable<T>out TT>IAsyncEnumerable<T>{ IAsyncEnumeratorIAsyncEnumerator<T><IAsyncEnumerator<T>TT>IAsyncEnumerator<T> GetAsyncEnumeratorIAsyncEnumerator<T> IAsyncEnumerable<T>.GetAsyncEnumerator()();}
public interface IAsyncEnumeratorIAsyncEnumerator<T><IAsyncEnumerator<T>out TT>IAsyncEnumerator<T> :IAsyncEnumerator<T> IAsyncDisposableIAsyncDisposable{ TT CurrentT IAsyncEnumerator<T>.Current { get; } ValueTaskValueTask<bool>Provides a value type that wraps a Task`1 and a TResult, only one of which is used.<ValueTask<bool>Provides a value type that wraps a Task`1 and a TResult, only one of which is used.boolboolRepresents a Boolean ( or ) value.>ValueTask<bool>Provides a value type that wraps a Task`1 and a TResult, only one of which is used. MoveNextAsyncValueTask<bool> IAsyncEnumerator<T>.MoveNextAsync()();}
public interface IAsyncDisposableIAsyncDisposable{ ValueTaskValueTaskProvides an awaitable result of an asynchronous operation. DisposeAsyncValueTask IAsyncDisposable.DisposeAsync()();}This is the definition of IAsyncEnumerable<T> from the C# 8.0 proposal, it should look very familiar, it is just IEnumerable<T> with an async MoveNext method, as you might expect.
We can now see the relationship with IObservable<T> and IEnumerable<T>.
Being in this familiar family means that we don’t have to learn new concepts to start consuming and composing operations over this type.
IAsyncEnumerableIAsyncEnumerable<Bar>Exposes an enumerator that provides asynchronous iteration over values of a specified type.<IAsyncEnumerable<Bar>Exposes an enumerator that provides asynchronous iteration over values of a specified type.BarBar>IAsyncEnumerable<Bar>Exposes an enumerator that provides asynchronous iteration over values of a specified type. ConvertGoodFoosToBarsIAsyncEnumerable<Bar> Example.ConvertGoodFoosToBars(IAsyncEnumerable<Foo> items)(IAsyncEnumerableIAsyncEnumerable<Foo>Exposes an enumerator that provides asynchronous iteration over values of a specified type.<IAsyncEnumerable<Foo>Exposes an enumerator that provides asynchronous iteration over values of a specified type.FooFoo>IAsyncEnumerable<Foo>Exposes an enumerator that provides asynchronous iteration over values of a specified type. itemsIAsyncEnumerable<Foo> items){ return itemsIAsyncEnumerable<Foo> items .WhereIAsyncEnumerable<Bar> Example.ConvertGoodFoosToBars(IAsyncEnumerable<Foo> items)(foo => foo.IsGoodIAsyncEnumerable<Bar> Example.ConvertGoodFoosToBars(IAsyncEnumerable<Foo> items)) .SelectIAsyncEnumerable<Bar> Example.ConvertGoodFoosToBars(IAsyncEnumerable<Foo> items)(foo => BarBar.FromFooBar Bar.FromFoo(Foo f)(foo));}These extension methods are immediately understandable to us and are ubiquitous in C# already.
Producing sequences
All of this would be pretty academic if we couldn’t generate sequences to be consumed. Today there are a few options.
1. Implement the IAsyncEnumerable<T> and IAsyncEnumerator<T> interfaces directly
You can do this, and for performance critical code, this might be the most suitable approach.
It does require a fair bit of boilerplate code however, so here is a starting point:
// A starting point for your own IAsyncEnumerable extensionspublic static class AsyncEnumerableExtensionsAsyncEnumerableExtensions{ public static IAsyncEnumerableIAsyncEnumerable<T>Exposes an enumerator that provides asynchronous iteration over values of a specified type.<IAsyncEnumerable<T>Exposes an enumerator that provides asynchronous iteration over values of a specified type.TT>IAsyncEnumerable<T>Exposes an enumerator that provides asynchronous iteration over values of a specified type. MyExtensionMethodIAsyncEnumerable<T> AsyncEnumerableExtensions.MyExtensionMethod<T>(IAsyncEnumerable<T> source)<IAsyncEnumerable<T> AsyncEnumerableExtensions.MyExtensionMethod<T>(IAsyncEnumerable<T> source)TIAsyncEnumerable<T> AsyncEnumerableExtensions.MyExtensionMethod<T>(IAsyncEnumerable<T> source)>IAsyncEnumerable<T> AsyncEnumerableExtensions.MyExtensionMethod<T>(IAsyncEnumerable<T> source)(this IAsyncEnumerableIAsyncEnumerable<T>Exposes an enumerator that provides asynchronous iteration over values of a specified type.<IAsyncEnumerable<T>Exposes an enumerator that provides asynchronous iteration over values of a specified type.TT>IAsyncEnumerable<T>Exposes an enumerator that provides asynchronous iteration over values of a specified type. sourceIAsyncEnumerable<T> source) { return new MyAsyncEnumerableAsyncEnumerableExtensions.MyAsyncEnumerable<T><AsyncEnumerableExtensions.MyAsyncEnumerable<T>TT>AsyncEnumerableExtensions.MyAsyncEnumerable<T>(sourceIAsyncEnumerable<T> source); }
public struct MyAsyncEnumerableAsyncEnumerableExtensions.MyAsyncEnumerable<T><AsyncEnumerableExtensions.MyAsyncEnumerable<T>TT>AsyncEnumerableExtensions.MyAsyncEnumerable<T> :AsyncEnumerableExtensions.MyAsyncEnumerable<T> IAsyncEnumerableIAsyncEnumerable<T>Exposes an enumerator that provides asynchronous iteration over values of a specified type.<IAsyncEnumerable<T>Exposes an enumerator that provides asynchronous iteration over values of a specified type.TT>IAsyncEnumerable<T>Exposes an enumerator that provides asynchronous iteration over values of a specified type. { readonly IAsyncEnumerableIAsyncEnumerable<T>Exposes an enumerator that provides asynchronous iteration over values of a specified type.<IAsyncEnumerable<T>Exposes an enumerator that provides asynchronous iteration over values of a specified type.TT>IAsyncEnumerable<T>Exposes an enumerator that provides asynchronous iteration over values of a specified type. enumerableIAsyncEnumerable<T> AsyncEnumerableExtensions.MyAsyncEnumerable<T>.enumerable;
internal MyAsyncEnumerableAsyncEnumerableExtensions.MyAsyncEnumerable<T>.MyAsyncEnumerable(IAsyncEnumerable<T> enumerable)(IAsyncEnumerableIAsyncEnumerable<T>Exposes an enumerator that provides asynchronous iteration over values of a specified type.<IAsyncEnumerable<T>Exposes an enumerator that provides asynchronous iteration over values of a specified type.TT>IAsyncEnumerable<T>Exposes an enumerator that provides asynchronous iteration over values of a specified type. enumerableIAsyncEnumerable<T> enumerable) { thisIAsyncEnumerable<T> AsyncEnumerableExtensions.MyAsyncEnumerable<T>.enumerable.enumerableIAsyncEnumerable<T> AsyncEnumerableExtensions.MyAsyncEnumerable<T>.enumerable = enumerableIAsyncEnumerable<T> enumerable; }
public IAsyncEnumeratorIAsyncEnumerator<T>Supports a simple asynchronous iteration over a generic collection.<IAsyncEnumerator<T>Supports a simple asynchronous iteration over a generic collection.TT>IAsyncEnumerator<T>Supports a simple asynchronous iteration over a generic collection. GetAsyncEnumeratorIAsyncEnumerator<T> AsyncEnumerableExtensions.MyAsyncEnumerable<T>.GetAsyncEnumerator()() { return new MyAsyncEnumeratorAsyncEnumerableExtensions.MyAsyncEnumerable<T>.MyAsyncEnumerator(enumerableIAsyncEnumerable<T> AsyncEnumerableExtensions.MyAsyncEnumerable<T>.enumerable.GetAsyncEnumeratorIAsyncEnumerator<T> IAsyncEnumerable<T>.GetAsyncEnumerator(CancellationToken cancellationToken = default(CancellationToken))Returns an enumerator that iterates asynchronously through the collection.ParameterscancellationToken — A CancellationToken that may be used to cancel the asynchronous iteration.ReturnsAn enumerator that can be used to iterate asynchronously through the collection.()); }
public struct MyAsyncEnumeratorAsyncEnumerableExtensions.MyAsyncEnumerable<T>.MyAsyncEnumerator :AsyncEnumerableExtensions.MyAsyncEnumerable<T>.MyAsyncEnumerator IAsyncEnumeratorIAsyncEnumerator<T>Supports a simple asynchronous iteration over a generic collection.<IAsyncEnumerator<T>Supports a simple asynchronous iteration over a generic collection.TT>IAsyncEnumerator<T>Supports a simple asynchronous iteration over a generic collection. { readonly IAsyncEnumeratorIAsyncEnumerator<T>Supports a simple asynchronous iteration over a generic collection.<IAsyncEnumerator<T>Supports a simple asynchronous iteration over a generic collection.TT>IAsyncEnumerator<T>Supports a simple asynchronous iteration over a generic collection. enumeratorIAsyncEnumerator<T> AsyncEnumerableExtensions.MyAsyncEnumerable<T>.MyAsyncEnumerator.enumerator;
internal MyAsyncEnumeratorAsyncEnumerableExtensions.MyAsyncEnumerable<T>.MyAsyncEnumerator.MyAsyncEnumerator(IAsyncEnumerator<T> enumerator)(IAsyncEnumeratorIAsyncEnumerator<T>Supports a simple asynchronous iteration over a generic collection.<IAsyncEnumerator<T>Supports a simple asynchronous iteration over a generic collection.TT>IAsyncEnumerator<T>Supports a simple asynchronous iteration over a generic collection. enumeratorIAsyncEnumerator<T> enumerator) { thisIAsyncEnumerator<T> AsyncEnumerableExtensions.MyAsyncEnumerable<T>.MyAsyncEnumerator.enumerator.enumeratorIAsyncEnumerator<T> AsyncEnumerableExtensions.MyAsyncEnumerable<T>.MyAsyncEnumerator.enumerator = enumeratorIAsyncEnumerator<T> enumerator; }
public ValueTaskValueTaskProvides an awaitable result of an asynchronous operation. DisposeAsyncValueTask AsyncEnumerableExtensions.MyAsyncEnumerable<T>.MyAsyncEnumerator.DisposeAsync()() { return enumeratorIAsyncEnumerator<T> AsyncEnumerableExtensions.MyAsyncEnumerable<T>.MyAsyncEnumerator.enumerator.DisposeAsyncValueTask IAsyncDisposable.DisposeAsync()Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources asynchronously.ReturnsA task that represents the asynchronous dispose operation.(); }
public TT CurrentT AsyncEnumerableExtensions.MyAsyncEnumerable<T>.MyAsyncEnumerator.Current => enumeratorIAsyncEnumerator<T> AsyncEnumerableExtensions.MyAsyncEnumerable<T>.MyAsyncEnumerator.enumerator.CurrentT IAsyncEnumerator<T>.CurrentGets the element in the collection at the current position of the enumerator.ReturnsThe element in the collection at the current position of the enumerator.;
public ValueTaskValueTask<bool>Provides a value type that wraps a Task`1 and a TResult, only one of which is used.<ValueTask<bool>Provides a value type that wraps a Task`1 and a TResult, only one of which is used.boolboolRepresents a Boolean ( or ) value.>ValueTask<bool>Provides a value type that wraps a Task`1 and a TResult, only one of which is used. MoveNextAsyncValueTask<bool> AsyncEnumerableExtensions.MyAsyncEnumerable<T>.MyAsyncEnumerator.MoveNextAsync()() { return enumeratorIAsyncEnumerator<T> AsyncEnumerableExtensions.MyAsyncEnumerable<T>.MyAsyncEnumerator.enumerator.MoveNextAsyncValueTask<bool> IAsyncEnumerator<T>.MoveNextAsync()Advances the enumerator asynchronously to the next element of the collection.ReturnsA ValueTask`1 that will complete with a result of if the enumerator was successfully advanced to the next element, or if the enumerator has passed the end of the collection.(); } } }}2. Use the static helper methods in Ix.NET
IAsyncEnumerableIAsyncEnumerable<int>Exposes an enumerator that provides asynchronous iteration over values of a specified type.<IAsyncEnumerable<int>Exposes an enumerator that provides asynchronous iteration over values of a specified type.intintRepresents a 32-bit signed integer.>IAsyncEnumerable<int>Exposes an enumerator that provides asynchronous iteration over values of a specified type. GenerateWithIxIAsyncEnumerable<int> Example.GenerateWithIx()(){ return AsyncEnumerableIAsyncEnumerable<int> Example.GenerateWithIx().CreateEnumerableIAsyncEnumerable<int> Example.GenerateWithIx()( () => { varintRepresents a 32-bit signed integer. currentint current = 0;
async TaskTask<bool>Represents an asynchronous operation that can return a value.<Task<bool>Represents an asynchronous operation that can return a value.boolboolRepresents a Boolean ( or ) value.>Task<bool>Represents an asynchronous operation that can return a value. fTask<bool> f(CancellationToken ct)(CancellationTokenCancellationTokenPropagates notification that operations should be canceled. ctCancellationToken ct) { await TaskTaskRepresents an asynchronous operation.. DelayTask Task.Delay(TimeSpan delay)Creates a task that completes after a specified time interval.Parametersdelay — The time span to wait before completing the returned task, or to wait indefinitely.ReturnsA task that represents the time delay.ExceptionsArgumentOutOfRangeException — delay represents a negative time interval other than . -or- The delay argument's TotalMilliseconds property is greater than 4294967294 on .NET 6 and later versions, or MaxValue on all previous versions.(TimeSpanTimeSpanRepresents a time interval..FromSecondsTimeSpan TimeSpan.FromSeconds(double value)Returns a TimeSpan that represents a specified number of seconds, where the specification is accurate to the nearest millisecond.Parametersvalue — A number of seconds, accurate to the nearest millisecond.ReturnsAn object that represents value.ExceptionsOverflowException — value is less than MinValue or greater than MaxValue. -or- value is PositiveInfinity. -or- value is NegativeInfinity.ArgumentException — value is equal to NaN.(0.5)); currentint current++Task<bool> f(CancellationToken ct); return true; }
return AsyncEnumerableIAsyncEnumerable<int> Example.GenerateWithIx().CreateEnumeratorIAsyncEnumerable<int> Example.GenerateWithIx()( moveNextIAsyncEnumerable<int> Example.GenerateWithIx():IAsyncEnumerable<int> Example.GenerateWithIx() fTask<bool> f(CancellationToken ct), currentIAsyncEnumerable<int> Example.GenerateWithIx():IAsyncEnumerable<int> Example.GenerateWithIx() () => currentint current, disposeIAsyncEnumerable<int> Example.GenerateWithIx():IAsyncEnumerable<int> Example.GenerateWithIx() () => { } ); });}3. Use CXuesong.AsyncEnumerableExtensions
I wanted to build something like this myself, and then I found this library, so I don’t need to! Credit to Chen, this is a great library.
// using CXuesong.AsyncEnumerableExtensionsasync TaskTaskRepresents an asynchronous operation. GeneratorTask Generator(IAsyncEnumerableSink<int> sink)(IAsyncEnumerableSinkIAsyncEnumerableSink<int><IAsyncEnumerableSink<int>intintRepresents a 32-bit signed integer.>IAsyncEnumerableSink<int> sinkIAsyncEnumerableSink<int> sink){ varintRepresents a 32-bit signed integer. iint i = 1; while (true) { await TaskTaskRepresents an asynchronous operation..DelayTask Task.Delay(TimeSpan delay)Creates a task that completes after a specified time interval.Parametersdelay — The time span to wait before completing the returned task, or to wait indefinitely.ReturnsA task that represents the time delay.ExceptionsArgumentOutOfRangeException — delay represents a negative time interval other than . -or- The delay argument's TotalMilliseconds property is greater than 4294967294 on .NET 6 and later versions, or MaxValue on all previous versions.(TimeSpanTimeSpanRepresents a time interval..FromSecondsTimeSpan TimeSpan.FromSeconds(double value)Returns a TimeSpan that represents a specified number of seconds, where the specification is accurate to the nearest millisecond.Parametersvalue — A number of seconds, accurate to the nearest millisecond.ReturnsAn object that represents value.ExceptionsOverflowException — value is less than MinValue or greater than MaxValue. -or- value is PositiveInfinity. -or- value is NegativeInfinity.ArgumentException — value is equal to NaN.(0.5)); await sinkIAsyncEnumerableSink<int> sink.YieldAndWaitTask IAsyncEnumerableSink<int>.YieldAndWait(int item)(iint i++Task IAsyncEnumerableSink<int>.YieldAndWait(int item)); }}
AsyncEnumerableFactoryAsyncEnumerableFactory.FromAsyncGeneratorobject AsyncEnumerableFactory.FromAsyncGenerator<int>(Func<IAsyncEnumerableSink<int>, Task> gen)<object AsyncEnumerableFactory.FromAsyncGenerator<int>(Func<IAsyncEnumerableSink<int>, Task> gen)intintRepresents a 32-bit signed integer.>object AsyncEnumerableFactory.FromAsyncGenerator<int>(Func<IAsyncEnumerableSink<int>, Task> gen)(GeneratorTask Generator(IAsyncEnumerableSink<int> sink));This library offers a very nice and simple way to express sequences. You build an async function that takes a IAsyncEnumberableSink<T> (defined by the library), and returns a Task. Now you can do your awaits, but when you want to yield an item to the sequence, you call sink.YieldAndWait(value) where sink is that parameter.
4. Coming soon to a C# 8.0 near you
Today you cannot use the async keyword and iterator methods together, so having an async iterator method would require a new language feature. Well good news, it’s in the works, take a sneak peak here.
Here is a snippet showing what it could look like.
static async IAsyncEnumerableIAsyncEnumerable<int>Exposes an enumerator that provides asynchronous iteration over values of a specified type.<IAsyncEnumerable<int>Exposes an enumerator that provides asynchronous iteration over values of a specified type.intintRepresents a 32-bit signed integer.>IAsyncEnumerable<int>Exposes an enumerator that provides asynchronous iteration over values of a specified type. MylteratorIAsyncEnumerable<int> Example.Mylterator()(){ try { for (intintRepresents a 32-bit signed integer. iint i = 0; iint i <IAsyncEnumerable<int> Example.Mylterator() 100; iint i++IAsyncEnumerable<int> Example.Mylterator()) { await TaskTaskRepresents an asynchronous operation..DelayTask Task.Delay(int millisecondsDelay)Creates a task that completes after a specified number of milliseconds.ParametersmillisecondsDelay — The number of milliseconds to wait before completing the returned task, or -1 to wait indefinitely.ReturnsA task that represents the time delay.ExceptionsArgumentOutOfRangeException — The millisecondsDelay argument is less than -1.(1000); yield return iint i; } } finally { await TaskTaskRepresents an asynchronous operation..DelayTask Task.Delay(int millisecondsDelay)Creates a task that completes after a specified number of milliseconds.ParametersmillisecondsDelay — The number of milliseconds to wait before completing the returned task, or -1 to wait indefinitely.ReturnsA task that represents the time delay.ExceptionsArgumentOutOfRangeException — The millisecondsDelay argument is less than -1.(200); ConsoleConsoleRepresents the standard input, output, and error streams for console applications. This class cannot be inherited..WriteLinevoid Console.WriteLine(string? value)Writes the specified string value, followed by the current line terminator, to the standard output stream.Parametersvalue — The value to write.ExceptionsIOException — An I/O error occurred.("finally"); }}Consuming sequencing
We can produce sequences, but that won’t be much use to us if we cannot consume them.
1. ForEachAsync
Just like the .ForEach(...) extension method on List<T>, we have .ForEachAsync(...) from Ix.Async, this lets us do work on each item, and gives us a Task to await to drive the whole chain of pull based work.
await seq.ForEachAsync(x => ConsoleConsoleRepresents the standard input, output, and error streams for console applications. This class cannot be inherited..WriteLinevoid Console.WriteLine()Writes the current line terminator to the standard output stream.ExceptionsIOException — An I/O error occurred.(x));Unfortunately, dogmatism fails here, ForEachAsync is suffixed with Async because it returns a Task and operates asynchronously, however the delegate it takes is synchronous, this led me to build a method that can take an async delegate and name it ForEachAsyncButActuallyAsync. :facepalm:
await seq.ForEachAsyncButActuallyAsync(x => ConsoleConsoleRepresents the standard input, output, and error streams for console applications. This class cannot be inherited..WriteLinevoid Console.WriteLine()Writes the current line terminator to the standard output stream.ExceptionsIOException — An I/O error occurred.(x));2. C# 8.0 foreach
Again, we have language support on the way. Here’s what it would look like:
varIAsyncEnumerable<int>Exposes an enumerator that provides asynchronous iteration over values of a specified type. asyncSequenceIAsyncEnumerable<int>? asyncSequence = GetMyAsyncSequenceIAsyncEnumerable<int> GetMyAsyncSequence(CancellationToken cancellationToken)(cancellationTokenCancellationToken cancellationToken:IAsyncEnumerable<int> GetMyAsyncSequence(CancellationToken cancellationToken) ctCancellationToken ct);await foreach (varintRepresents a 32-bit signed integer. itemint item in asyncSequenceIAsyncEnumerable<int>? asyncSequence){..Range Range.All.get.}Design Decisions
One of the problems that has meant that we’ve had to wait so long a first class IAsyncEnumberable<T> and language features is because there are many design decisions that need answering, for example;
- Does
IAsyncEnumerator<T>implementIDisposableor a new async version (IAsyncDisposable)? UpdateIAsyncDisposableit is! - If there is going to be an
IAsyncDisposable, should the language support theusingsyntax for it? - Does the
CancellationTokenget passed intoMoveNexteach move orGetEnumeratoronce? UpdateCancellationTokens are not going to be handled by syntax, so you should flow it into theIAsyncEnumerable<T>types yourself. - Should it be
MoveNext, orMoveNextAsync? UpdateMoveNextAsyncwins! - Should
MoveNextAsyncreturn aTask<bool>or aValueTask<bool>? UpdateValueTask<bool>has it! - In the foreach syntax, where does the
awaitmodifier go? Outside the brackets? (Yes, of course, what sort of monster do you take me for?) - In the foreach syntax, how do you do the equivalent of
.ConfigureAwait(false)? Update like this. - Will the foreach syntax look for the type, or the pattern?
awaitdoesn’t just apply toTaskfor example.
and that’s just what comes immediately to mind, the more you think, the more you uncover.
Who is using it today?
There are a couple of large projects using this today:
- Entity Framework Core - Currently using an internal definition, but there is talk of plans to use whatever comes in C# 8.
- Google Cloud Platform Libraries - This one was a bit of a surprise to me. If you install any Google Cloud package, it will reference their Core package, which uses and references Ix.Async. One of the members of the team that builds this is (the) Jon Skeet, so that’s quite an endorsement!
Stay tuned, there is more to come on this topic.
Comments