DEV Community

Alex Allen
Alex Allen

Posted on • Edited on • Originally published at blog.lxalln.com

ForEach Async Woes

I was investigating a bug last week when I stumbled upon a block of code that looked like this:

public async Task Method(List<Animal> collection)
{ 
    // do something async

    collection.ForEach(async v => await _mediator.Send(new Command(v.Id), cancellationToken));
}
Enter fullscreen mode Exit fullscreen mode

I wrote this without thinking, I very rarely use List.ForEach() for enumerating through a list, but for some reason I did here. I probably got carried away with the because I can, rather than because I should.

Unfortunately this code is broken, it does not work the way I expected.
Because there is no await on the collection.ForEach... execution continues on past and the method exits.

Switching to a standard foreach(...) loop and awaiting inside in each enumeration will solve this problem.

public async Task Method(List<Animal> collection)
{
    // do something async

    foreach(var v in collection)
    {
        await _mediator.Send(new Command(v.Id), cancellationToken);
    }
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)