0

What's best practice when creating multiple tasks for Task.WhenAll()?

Is there a difference between these two async-await alternatives below in terms of performance, and/or behavior under an exception?

They both work, but is there any difference?

Alternative 1:

private async void Button_Click(object sender, RoutedEventArgs e)
{
   // call DoWork() to prepare data
   await Task.WhenAll(myObjects.Select(o => Task.Run(() => o.DoWork()));

  // update ui ...
}

Alternative 2:

private async void Button_Click(object sender, RoutedEventArgs e)
{
   // call DoWork () to prepare data - note the async-await around the return Task
   await Task.WhenAll(myObjects.Select(async o => await Task.Run(() => o.DoWork()));

   // update ui...
}

Thank you.

Fredrik
  • 2,247
  • 18
  • 21
  • 1
    What work is done in `DoWork`, why do you need `Task.Run`? Method 2 introduces an extra state machine. 1 is better. If you are not doing anything after an await statement then just return the task. – Peter Bons Feb 21 '17 at 13:33
  • 1
    See ["Any difference between “await Task.Run(); return;” and “return Task.Run()”?](http://stackoverflow.com/q/21033150/1768303). – noseratio Feb 21 '17 at 13:45

0 Answers0