C# 8 asynchronous streams

C# 8 asynchronous streams

.NET Core 3.1 (December 2019) includes support for C# 8, a new major
version of the C# programming language. In this series of articles, we’ll look at the new features in .NET’s main programming language. This first article, in particular, looks at asynchronous streams. This feature makes it easy to create and consume asynchronous enumerables, so before getting into the new feature, you first need to understand the IEnumerable interface.

Note: C# 8 can be used with the .NET Core 3.1 SDK, which is available on Red Hat Enterprise Linux, Fedora, Windows, macOS, and on other Linux distributions.

A brief history of IEnumerable

The classic IEnumerable<T> has been around since .NET Framework 2 (2005). This interface provides us with a type-safe way to iterate over any collection.

The iteration is based on the IEnumerator<T> type:

public interface IEnumerator<T> : IDisposable
{
    bool MoveNext();
    T Current;
    void Reset();
}

You can see that the MoveNext method moves us to the next element. It returns true when there is an element, and then Current returns that element. The Reset method provides a way to reset the iterator to the start. The IEnumerable<T> is IDisposable, so its implementation might perform resource cleanup. Note that the generic parameter is an out-parameter. This keyword enables casting the IEnumerable<T> to a base type IEnumerable<TBase>.

The foreach keyword allows the easy consumption of IEnumerables.

foreach (var item in myEnumerable)
   Console.WriteLine($”* {item}”);

The yield keyword makes it easy to implement an IEnumerable<T> with a method, and lets the compiler figure out how to implement the interface. For example:

IEnumerable<int> MyEnumerable
{
    get
    {
        for (int i = 0; i < 3; i++)
            yield return i;
        yield return 100;
    }
}

This code causes the compiler to generate a type that implements IEnumerable<int>, which tracks enough information to know where we are in the [0, 1, 2, 100] iteration.

The power of IEnumerable<T> shines with C# 3’s Language-Integrated Query (2007) which allows IEnumerable<T> to be transformed, combined and filtered. For example:

var queryLondonCustomers = from cust in customers
                           where cust.City == "London"
                           select cust.Name;

The customers in this example refer to an IEnumerable<Customer>. We filter by city, which gives us (again) an IEnumerable<Customer>. Then, finally, we select the name so our resulting type is an IEnumerable<string>.

Everything you need to grow your career.

With your free Red Hat Developer program membership, unlock our library of cheat sheets and ebooks on next-generation application development.

SIGN UP

Asynchronous streams

Asynchronous streams use the IAsyncEnumerator<T> type. This type is similar to IEnumerator<T>, but with a Move method that is async (it returns a Task-like type):

ValueTask<T> MoveNextAsync();

Thanks to the async Move method, we can now asynchronously wait for the next item. This means that we can wait without blocking a thread. Note that the method returns a ValueTask, which makes the call allocation-free when the next item is already available. You can read more about ValueTask in Understanding the Whys, Whats, and Whens of ValueTask.

IAsyncEnumerable<T> is a good match for events that happen infrequently, or data that is received asynchronously (for example, over the network). Because the IAsyncEnumerable knows at what rate we are pulling the items, it can be smart about how much data it buffers, and when it asks the upstream source for more data.

As with IEnumerable<T>, C# provides first-class support for implementing IAsyncEnumerables. For example:

static async IAsyncEnumerable<string> GetTopSearchResults(string term)
{
    using var client = new HttpClient();
    yield return await client.GetStringAsync($"https://www.google.com?q={term}");
    yield return await client.GetStringAsync($"https://www.bing.com?q={term}");
}

For consuming, we use the await foreach keyword as you can see in this example:

await foreach (var item in GetTopSearchResults("test"))
{
    System.Console.WriteLine(item);
}

Cancellation

The default pattern for canceling asynchronous methods is by using a CancellationToken. We can add a CancellationToken to our method like so:

static async IAsyncEnumerable GetTopSearchResults(string term, [EnumeratorCancellation]CancellationToken ct = default)
{
    using var client = new HttpClient();
    // GetStringAsync doesn't accept a CancellationToken, Dispose the client to cancel.
    using var ctr = ct.Register(s => ((HttpClient)s).Dispose(), client);
    yield return await client.GetStringAsync($"https://www.google.com?q={term}");
    yield return await client.GetStringAsync($"https://www.bing.com?q={term}");
}

We can pass the CancellationToken as an argument when we invoke the method:

var cts = new CancellationTokenSource(millisecondsDelay: 1000);
await foreach (var result in GetTopSearchResults("dotnet", cts.Token))

Or alternatively, we can use the WithCancellation method, which makes the compiler pass the value to the argument with the EnumeratorCancellation attribute. For example:

var cts = new CancellationTokenSource(millisecondsDelay: 1000);
await foreach (var result in GetTopSearchResults("dotnet").WithCancellation(cts.Token))

ConfigureAwait(false)

When an async method completes asynchronously, it uses the invocation SynchronizationContext to continue. This feature puts us back into the main UI thread when invoking an async method in a Win32 Forms/WPF application. It facilitates GUI programming because UI controls should only be updated from the UI thread. When this feature is not needed, the overhead can be avoided by adding ConfigureAwait(false) to the task that is awaited, as you can see here:

await SomeMethodAsync().ConfigureAwait(false);

We can apply ConfigureAwait(false) to the MoveNextAsync calls that are generated by the foreach statement like this:

await foreach (var result in GetTopSearchResults("dotnet").ConfigureAwait(false))

Note that this option applies to the MoveNextAsync calls. You should also add ConfigureAwait(false) to the awaited methods inside the GetTopSearchResults method.

Conclusion

In this article, you’ve learned how C# 8 async streams makes it easy to create and consume asynchronous enumerables. Async streams is an interesting feature, especially for applications that are consuming data/events that are received from the network. In the next article in this series, we will look at C# 8’s extended pattern matching.

Share