BT

Facilitating the Spread of Knowledge and Innovation in Professional Software Development

Write for InfoQ

Topics

Choose your language

InfoQ Homepage News C# Futures: Asynchronous Sequences

C# Futures: Asynchronous Sequences

Leia em Português

The async/await syntax in C# was well received, but now developers are asking for more. Specifically, they want to be able to return more than one value from their asynchronous function using a “yield return” like syntax. This capability is being referred to as “asynchronous sequences” in a new proposal for C# 7.

There are two patterns that proponents of the proposal wish to see:

  • IObservable<T>, which is the bases of Reactive Extensions (Rx) and is part of .NET 4.0
  • IAsyncEnumerable<T>, which was introduced in the Interactive Extensions (Ix) project and is used in Entity Framework 7.

Defining the Producer

HaloFour writes,

From a sequence producer point of view they would behave a little differently in that yield return for IObservable<T> would likely continue executing immediately whereas for IAsyncEnumerable<T> it would wait until the next invocation of MoveNext() .

It is generally accepted that for the push model, Observable.Create is sufficient. The pull model, which is based on IAsyncEnumerable<T>, is rather tedious to implement. So this is where an async version of iterator functions and the “yield return” statement would be very useful.

Defining the Consumer

HaloFour continues,

From the consumer point of view they should probably behave the same way. Observable.ForEach allows the action to execute concurrently and I think that it would probably be pretty unintuitive to allow the foreach body to have multiple concurrent threads (assuming that they're not being dispatched through a SynchronizationContext ). If the implementation is similar to how await works whatever intermediary ( SequenceAwaiter , etc.) could handle the details of buffering the results from an IObservable<T> or an extension method could just turn it into an IAsyncEnumerable<T> .

No examples of the syntax were offered yet, but presumably it would look something like this:

await foreach (var item in AsyncSource)

Rate this Article

Adoption
Style

BT