DEV Community

Discussion on: A Simple Trick to Boost Performance of Async Code in C#

Collapse
 
davidkroell profile image
David Kröll

Yes, you are absolutely right. Thank you for your Feedback.

In this case there is no difference. The only thing which would make a difference is, that you could ensure that after awaiting the Task.WhenAll, all supplied tasks are completed as well and you can get the results with the property Result instead of awaiting them again.

Thread Thread
 
andreasjakof profile image
Andreas Jakof

And this is also the Performance gain, you could have, when calling and awaiting them individually. Only the tasks, which give some imideatly needed results, need to be finished, potentially giving longer running tasks more time to finish, while already working with some results, that are needed in an earlier step.

In the making breakfast example this would be boiling an egg starting in cold water (6:30 min) and toasting a bread (2:00 min) butter it (0:30 min) and adding some Jam (0:30 min).

You start the egg and the toasting at the same time. In your case, you await both, which means you start buttering the toast, after the egg is finished. You could use .ContinueWith(…), but that is another approach alltogether.

If you know that (like in our case) the egg will always take longer than the other tasks together, you could

  • start the egg and „keep track“ by storing it in a variable.
  • toast and immediately await it
  • butter + await and Jam + await
  • await the egg. => 6:30 min instead of 7:30 min

You could also (and this case is a perfekt example for it)

  • start the egg and store the task
  • start toast - continuewith butter - continuewith jam and store the task
  • await both (Task.WhenAll or individually) => 6:30 min as well
Thread Thread
 
davidkroell profile image
David Kröll

Yes thats true if you can determine the runtimes that exact this would be a neat option.

Thread Thread
 
andreasjakof profile image
Andreas Jakof

Therefore the last option with ContinueWith is the better (best?) solution. Even if you don‘t know the runtimes exacty. It makes sure, run the tasks in parallel, that can while also making Visual, that these tasks (toast, butter, jam) are in sequence.

Nevertheless it is usually enough to know that A takes longer than B to start them in the „right“ order.