.NET asynchronous programming: Choice of await Task.Run
and await Async
methods
In .NET asynchronous programming, the use of await Task.Run
and await
asynchronous methods is often confusing. This article will illustrate the difference between the two through a concrete scenario and provide a comprehensive understanding.
Scene:
Consider the following two code snippets:
<code class="language-csharp">await Task.Run(() => LongProcess());</code>
and
<code class="language-csharp">await LongProcess();</code>
where LongProcess
is an asynchronous method containing asynchronous calls, such as await ExecuteReaderAsync()
.
Answer:
In this particular scenario, there is no significant difference between the two methods. Both use the await
keyword to return control to the caller before the asynchronous operation in LongProcess
is completed.
The nature of asynchronous execution
Contrary to popular belief, asynchronous code does not execute on multiple threads. Instead, it executes on a thread, utilizing a technique called "context switching."
When an asynchronous function calls another asynchronous function, the current thread temporarily suspends the execution of the caller and continues the execution of the callee. The operating system then assigns the suspended thread to other available tasks.
However, once a await
statement is encountered in the callee, the current thread returns to the caller, effectively resuming the caller's execution.
Directawait
Advantages of asynchronous methods
In the given scenario, since LongProcess
is already an async method, there is no need to explicitly wrap it in await
before Task.Run
it. Direct await
asynchronous methods allow threads to immediately start performing other tasks while waiting for LongProcess
to complete.
Task.Run
usage scenarios
Task.Run
has its specific use cases, for example:
Summary
In the scenario given, both methods are functionally equivalent. However, the direct await
asynchronous approach is preferable as it reduces thread switching and allows for more efficient use of the thread pool.
The above is the detailed content of Await Task.Run vs. Await Async: When Should You Choose Which?. For more information, please follow other related articles on the PHP Chinese website!