When should I await my asyncs?
Solution 1:
My understanding is: because the methods in both the furniture and appliance services in the above require House, they will wait for House to be available before continuing.
Your understanding is wrong. The methods that require House, they are not waiting for you to get House because you need it. They don't resolve their dependencies and when to wait for code or not on their own. The code waits to get Houses because you have await
before it. It's not aware of what's going to happen next.
Then, both methods that need House will run, but the second method (GetAppliancesForHouse) will not wait for the first to finish before starting.
Similarly, the GetAppliancesForHouse
won't have its own understanding if it should wait or not based on the dependencies. GetAppliancesForHouse
won't run, because your code says to await GetFurnitureForHouse
before it first. Your code will always run sequentially.
Jim's understanding is: that we should await both methods only when they are needed. So that they will both run parallel to each other.
That's generally true. As others have pointed out, the code still might run not in parallel depending on other factors. Also, there might be legitimate reasons to not want to run code in parallel.
He thinks that doing it my way will result in the second method waiting for the first, ie: GetAppliancesForHouse waiting for GetFurnitureForHouse.
He's right.
To see what happens exactly, you can put breakpoints and see what happens after each line. In Jims case, after going from Furniture to Appliances, furniture variable won't have the value yet, it's still a task, but you are already in the next line.
With your case, going to Appliances line, you will see that Furniture already has the value, since it waited for it.
Solution 2:
Neither of you is correct, see the answer by @erndob for the reasons. However, one of the questions is not answered:
When should we await?
- Do you want the work to be done sequentially? Use your way.
- Do you want the work to be done in parallel? Use Jim's way.
Note: Jim's way will not actually run in parallel if the Task Scheduler used is unable to run both Tasks at the same time, for example, due to lack of system resources (thanks @AdamSimon).