VSO
VSO

Reputation: 12646

Any point to List<T>.ForEach() with Async?

I ran into this piece of code:

items.ForEach(async item =>
{
     doSomeStuff();   
     await mongoItems.FindOneAndUpdateAsync(mongoMumboJumbo);
     await AddBlah(SqlMumboJumbo);
});

Is there any point in making this a .forEach delegate, or could it be just a normal foreach loop? As long as the function that contains the loop is in is async, this would be async by default?

Upvotes: 5

Views: 1419

Answers (2)

Yuval Itzchakov
Yuval Itzchakov

Reputation: 149538

The delegate received by ForEach is an Action<T>:

public void ForEach(Action<T> action)

This means, that any async delegate you use inside it will effectively turn into an async void method. These are "fire and forget" style of execution. This means your foreach wont finish asynchronously waiting before continuing to invoke the delegate on the next item in the list, which might be an undesired behavior.

Use regular foreach instead.

Side note - foreach VS ForEach by Eric Lippert, great blog post.

Upvotes: 7

Harald Coppoolse
Harald Coppoolse

Reputation: 30464

You don't know when your function is finished, nor the result of the function. If you start each calculation in a separate Task, you can await Task.WhenAll and interpret the results, even catch exceptions:

private async Task ActionAsync(T item)
{
    doSomeStuff();   
    await mongoItems.FindOneAndUpdateAsync(mongoMumboJumbo);
    await AddBlah(SqlMumboJumbo);
}

private async Task MyFunction(IEnumerable<T> items)
{
    try
    {
        foreach (var item in items)
        {
            tasks.Add( ActionAsync(item) )
        }
        // while all actions are running do something useful
        // when needed await for all tasks to finish:
        await Task.WhenAll(tasks);
        // interpret the result of each action using property Task.Result
    }
    catch (AggregateException exc)
    {
        ProcessAggregateException(exc);
    }
}

The aggregateException is thrown when any of your task throws an exception. If contains all exceptions thrown by all your tasks.

Upvotes: 2

Related Questions