Why use Async/await all the way down

前端 未结 5 1201
情深已故
情深已故 2020-11-29 07:12

I would like to get some clarification on what is the added benefit of using of Await and Async all the way down.

If my application is calling await Func1()

5条回答
  •  甜味超标
    2020-11-29 08:00

    Usually, the reasoning behind async/await goes the other way around:

    For whatever reason, you decide that Func2 would be easier to write using await. So you simplify the method by adding the desired awaits, meaning you also have to change the method signature (it will now include the async keyword and a return type of Task or Task).

    Because the return type has changed, you can no longer call Func2 like you used to (var result = Func2();), so you're now required to change the calling method, Func1. The easiest way to adapt Func1 will often be to make it async too, and await Func2().

    Then, for the same reason (changed signature), you will need to change all calls to Func1, and so on until you get to some kind of entry point (either a UI event handler, or your Main method, or something else).

    So you don't start making the "outermost" method async and follow through to the "inner" (called) methods; you usually make things async while going in the opposite direction (from the "innermost" methods back to the calling ones). This other answer calls this idea "async all the way up".

提交回复
热议问题