Comparison with directly -when does return await
? Task<T>
await
In asynchronous programming, you can write a method of returning to use the
object. Although these two methods are equivalent in most cases, in some specific scenarios, the use of Task<T>
asynchronous methods is necessary. return await
Task<T>
A key difference is when using these methods with return await
blocks with
using
In the first method, the try
object will be released immediately after
Task<someresult> DoSomethingAsync() { using (var foo = new Foo()) { return foo.DoAnotherThingAsync(); } } async Task<someresult> DoSomethingAsync() { using (var foo = new Foo()) { return await foo.DoAnotherThingAsync(); } }
Foo
On the contrary, the second method of using DoAnotherThingAsync()
ensures that the DoAnotherThingAsync()
object is released only after Foo
completed its task. This provides expected behavior.
Therefore, when you need to ensure the correct release or managing certain resources in the asynchronous operation involving an asynchronous operation involving an object of the await
or an interface, you must use an asynchronous method with DoAnotherThingAsync()
. Foo
The above is the detailed content of Async Methods: `return await` vs. Directly Returning `Task` – When is `await` Necessary?. For more information, please follow other related articles on the PHP Chinese website!