Home > Back-end >  await IAsyncEnumerable<T> where is it used?
await IAsyncEnumerable<T> where is it used?

Time:08-24

It says here:

Question. In addition to the specified example with foreach, is it possible to use more the await with IAsyncEnumerable<T> somehow, or is it designed specially for foreach? I think yes, but not sure. Perhaps there are other purposes.

await foreach (var number in GetNumbersAsync())
{
    Console.WriteLine(number);
}

async IAsyncEnumerable<int> GetNumbersAsync()
{
    for (int i = 0; i < 10; i  )
    {
        await Task.Delay(100);
        yield return i;
    }
}

CodePudding user response:

As Jeremy Lakeman said in the comments, you can use it however you want. There is nothing magic about it. Simply call .GetAsyncEnumerator() on your IAsyncEnumerable and then you can use that as you would a regular enumerator, but with async support.

Example:

IAsyncEnumerator<int> e = GetNumbersAsync().GetAsyncEnumerator();
try
{
  while (await e.MoveNextAsync())
    Console.Write(e.Current   " ");
}
finally {
  if (e != null)
    await e.DisposeAsync();
}

The sample was taken from here: https://docs.microsoft.com/en-us/archive/msdn-magazine/2019/november/csharp-iterating-with-async-enumerables-in-csharp-8

CodePudding user response:

When compiled, foreach becomes like:

IAsyncEnumerator<int> e = RangeAsync(10, 3).GetAsyncEnumerator();
try
{
  while (await e.MoveNextAsync()) Console.Write(e.Current   " ");
}
finally { if (e != null) await e.DisposeAsync(); }

Further

the github.com/dotnet/reactive project includes the System.Linq.Async library, which provides a full set of such extension methods for operating on IAsyncEnumerable. You can include this library from NuGet in your project, and have access to a wide array of helpful extension methods for operating over IAsyncEnumerable objects.

  • Related