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?
The delegate received by
ForEach
is anAction<T>
: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.
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:
The aggregateException is thrown when any of your task throws an exception. If contains all exceptions thrown by all your tasks.