1

I am using some API that returns me an IEnumerator child Instance i want to do some function on each object returned

I usualy use

while(Enumerator.MoveNext())
{
    DoSomething(Enumerator.current);
}

I don't have IEnumerable Object and I want to DoSomething with each object asynchronously

I don't want to get IEnumerable from IEnumerator for performance issues.

What else can i do to loop async with IEnumerator

M. Khalil
  • 43
  • 1
  • 8

1 Answers1

5

C# 8.0 has Async Enumerable feature.

static async Task Main(string[] args)
{
    await foreach (var dataPoint in FetchIOTData())
    {
        Console.WriteLine(dataPoint);
    }

    Console.ReadLine();
}

static async IAsyncEnumerable<int> FetchIOTData()
{
    for (int i = 1; i <= 10; i++)
    {
        await Task.Delay(1000);//Simulate waiting for data to come through. 
        yield return i;
    }
}
AgentFire
  • 8,944
  • 8
  • 43
  • 90