Reputation: 11
I need to write a method that returns an IEnumerable of objects in an async-fashion and a Foreach loop that goes through the returned IEnumerable of objects from that method. I'm using .Net Core 2 and not quite sure how to approach this task. Is it possible in .netcore2 to return an async IEnumerable?
public async IEnumerable<int> MethodThatReturnsObjectsAsync()
{
}
foreach(int item in await MethodThatReturnsObjectsAsync())
{
Action(item);
}
Thanks in advance.
Upvotes: 0
Views: 788
Reputation: 10889
No, unfortunately it is not possible at the moment. .NET Core 3.0 will ship with an IAsyncEnumerable
which can do that, but that's a preview for now.
Upvotes: 0
Reputation: 81493
Yes its fine, it only gets called once. It only creates one state machine (If your calling method is an async
method.. i.e async Task
, async Task<T>
, Async void
)
In your case
public async Task<IEnumerable<int>> Test(Action<something> action)
{
foreach (int item in await MethodThatReturnsObjectsAsync())
{
action(item);
}
...
return ...
}
private static async Task<IEnumerable<int>> MethodThatReturnsObjectsAsync()
{
throw new NotImplementedException();
}
Upvotes: 1