I suggest you ...

Add async foreach to C# and IAsyncEnumerator to .NET

• C# feature 1 (foreach-await):

foreach (var item in AWAIT asyncEnumerable) { ... }

• .NET interfaces

public interface IAsyncEnumerable<T> : IEnumerable<T> {
IAsyncEnumerator<T> GetAsyncEnumerator();
}

public interface IAsyncEnumerator<T> : IEnumerator<T> {
Task<bool> MoveNextAsync();
}

• C# feature 2 (async-yield):

async IAsyncEnumerable<XmlNodeType> TokenizeXmlAsync(XmlReader reader) {
while (await reader.ReadAsync()) {
yield reader.NodeType;
}
}

• Why

Imagine a scenario when you run a SQL query and read results row by row, but you don't won't to block a thread in your app because you are waiting on a reader to read and parse the next row from the network stream, and you want to save your time on development:

foreach (var row in await resultRowSet) { ... }

VS.

using (var enumerator = resultRowSet.GetAsyncEnumerator()) {
while (await enumerator.MoveNextAsync()) {
var row = enumerator.Current;
...
}
}

And:

IEnumerable<DbRow> EnumerateRows(DbStream stream) {
while (true) {
var entry= ReadNextEntry(stream);
if (entry.Type == EntryType.Row) {
var row = ReadRow(stream);
yield return row;
} else {
break;
}
}
}

VS.

async IAsyncEnumerable<DbRow> EnumerateRowsAsync(DbStream stream) {
while (true) {
var entry= await ReadNextEntryAsync(stream);
if (entry.Type == EntryType.Row) {
var row = await ReadRowAsync(stream);
yield return row;
} else {
break;
}
}
}

43 votes
Vote
Sign in
(thinking…)
Sign in with: facebook google
Signed in as (Sign out)
You have left! (?) (thinking…)
Serge Semenov shared this idea  ·   ·  Flag idea as inappropriate…  ·  Admin →

1 comment

Sign in
(thinking…)
Sign in with: facebook google
Signed in as (Sign out)
Submitting...

Feedback and Knowledge Base