The return value in asynchronous programming: directly return
or use ? Task
return await
In asynchronous programming, developers are often entangled in returning or using the
through a specific scene. Task<T>
return await
Why choose return await
instead of returning
Under normal circumstances, return return await
and Task<T>
structural functions. However, there are subtle differences between the two when the statement or more commonly used in the block.
Please consider the following code example: Task<T>
return await
using
try
Scene analysis return await
In the first method (
), the<code class="language-csharp">Task<SomeResult> DoSomethingAsync() { using (var foo = new Foo()) { return foo.DoAnotherThingAsync(); } }</code>
<code class="language-csharp">async Task<SomeResult> DoSomethingAsync() { using (var foo = new Foo()) { return await foo.DoAnotherThingAsync(); } }</code>
method returns. This may happen for a long time before the method is completed, and errors are caused by premature release.
On the contrary, the second method (using) will wait before the await
method is completed, and then release using
. This ensures the correct release and normal operation of . DoAnotherThingAsync()
Foo
Conclusion Foo
Although await
is usually equivalent to DoAnotherThingAsync()
function directly, the latter is better than using the Foo
statement or in the Foo
scene in the
The above is the detailed content of Should You Return `Task` Directly or Use `return await` in Asynchronous Programming?. For more information, please follow other related articles on the PHP Chinese website!