vs. Back to TASK directly: return await
The importance in await
blocks using
is equal to the use of return await
, there are subtle but important differences between the two when using the using
block packaging method.
Considering the following two same methods:
Task<TResult> DoSomethingAsync() { using (var foo = new Foo()) { return foo.DoAnotherThingAsync(); } } async Task<TResult> DoSomethingAsync() { using (var foo = new Foo()) { return await foo.DoAnotherThingAsync(); } }
In the first method, when returning to TASK directly, the using
block will immediately release the DoAnotherThingAsync
object to the Foo
method to return the control code and immediately release the DoAnotherThingAsync
object. However, the method may not be completed, which may lead to potential mistakes.
On the contrary, when using return await
, the control flow will wait before the continuing execution. DoAnotherThingAsync
is completed. This ensures that blocks are released only after the asynchronous operation is fully executed. Therefore, the second method will work normally, and the first method may be released. using
Foo
The above is the detailed content of `return await` vs. Directly Returning a Task: Why Does `await` Matter in `using` Blocks?. For more information, please follow other related articles on the PHP Chinese website!