This new C# 8.0 feature should come in handy and rounds out the handling of streaming data in straightforward way, taking advantage of all the good things we’ve come to know from Linq. So, read on to learn how to play with this.
Project setup for new projects
- Install the latest .Net Core 3.1 (or later)
Using IAsyncEnumerable
Instead of returning an IEnumerable we want to access the stream asynchronously. This is a simple change in the return type to IAsyncEnumerable. For example:
async IAsyncEnumerable<string> getLines() {
var rdr = new StreamReader(@"c:\readme.md");
while (!rdr.EndOfStream) {
var line = await rdr.ReadLineAsync();
yield return line;
}
}
To consume this data, we can use Linq. Note: the query syntax is unchanged, but to process the result, we need the “await” keyword before iterating over it.
var res = from l in getLines() where l.StartsWith("#") select l;
await foreach(var line in res) {
System.Console.WriteLine(line);
}
Using Fluent syntax, we have a couple alternatives. Either await and project and execute in one step – processing the full list as Enumerable.
var ares = await getLines().Where(l=>l.StartsWith("#")).Select(l=>l)
.ToListAsync();
foreach(var line in ares) {
System.Console.WriteLine(line);
}
Or, project and await on the iteration (as in the first example above). In this case “res” is type of AsyncEnumerable+WhereSelectEnumerableAsyncIterator…
res = getLines().Where(l=>l.StartsWith("#")).Select(l=>l);
await foreach(var line in res) {
System.Console.WriteLine(line);
}
That about wraps it up. The example code can be found here:
github.com/oshea00/CSharp8-preview