The subtle difference in asynchronous programming:
and directly return return await
Task<T>
In asynchronous programming, the choice of and directly returning
return await
Task<T>
The advantages of
This subtle but important difference is appeared in return await
in the blocks. Consider the following example:
In this example, if try
is an asynchronous operation that runs for a long time, the using
statement will release return await
immediately after
<code class="language-csharp">Task<someresult> DoSomethingAsync() { using (var foo = new Foo()) { return foo.DoAnotherThingAsync(); } }</code>
On the contrary, the use of foo.DoAnotherThingAsync()
in the asynchronous method is different: using
DoAnotherThingAsync()
foo
In this case, DoAnotherThingAsync()
Keywords ensure that asynchronous operations are completed before
. This behavior is in line with the expected function and prevents potential errors. return await
<code class="language-csharp">async Task<someresult> DoSomethingAsync() { using (var foo = new Foo()) { return await foo.DoAnotherThingAsync(); } }</code>
await
Although using
is enough to return directly in most cases, when the foo
block is used in the
structure provides a key advantage. By ensuring the correct release of resources, help maintain code integrity and prevent accidents.
The above is the detailed content of Return Await vs. Direct Task Return: When Does it Matter?. For more information, please follow other related articles on the PHP Chinese website!