When to Return or Await at the End of an Async Method
In an asynchronous method returning a Task, one can opt to either await a subsequent asynchronous call or simply return its task. This decision has certain consequences that should be taken into consideration.
Option A: Returning a Task
In this scenario, exemplified by the FooAsync method, the method directly returns the Task produced by BazAsync. This approach is suitable for keeping the method declaration synchronous, enabling synchronous exception handling and argument validation. It also requires one fewer task to be tracked by the runtime.
Option B: Awaiting the Task
In the BarAsync method, the await keyword is used to await the completion of BazAsync. This is necessary when the asynchronous method itself is declared as an asynchronous method. While this may introduce an additional task, it ensures that the method can be altered later to perform additional post-processing tasks without altering its return type.
Exceptions
It is important to note that synchronous code within an asynchronous method will synchronously throw exceptions. If asynchronous exception handling is desired, the method should be declared as asynchronous.
Overloading
Returning the Task of an asynchronous call is commonly employed in method overloading to provide an asynchronous alternative to a synchronous method.
Conclusion
The choice between returning or awaiting the Task of another asynchronous call depends on the specific requirements of the method. Returning the Task maintains synchronous behavior while reducing the number of tasks, whereas awaiting the Task ensures flexibility in post-processing but incurs the overhead of an additional task.
The above is the detailed content of Should I Return or Await a Task at the End of an Async Method?. For more information, please follow other related articles on the PHP Chinese website!