Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

await IAsyncEnumerable<T> where is it used?

It says here:

Starting with C# 8.0, IAsyncEnumerable, for an async method that
returns an async stream.

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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;
    }
}

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading