Any point to List.ForEach() with Async?

2019-06-21 13:18发布

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?

2条回答
相关推荐>>
2楼-- · 2019-06-21 13:22

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.

查看更多
叛逆
3楼-- · 2019-06-21 13:31

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.

查看更多
登录 后发表回答