Home >Backend Development >C++ >Async/Await in C#: To Await or Not to Await? The Impact on Execution
Usage of Async/Await in C#: To wait or not to wait? Impact on execution
The following code contains six calls to the Callee
method, each executed in a different way:
Asynchronous call (Fire-and-forget): Callee
The method is called asynchronously and does not wait. The method runs asynchronously in the background, and the calling method continues execution immediately.
Wait for an asynchronous call: The Callee
method is called and use await
to wait for its completion. The calling method will wait for the Callee
method to complete before continuing to execute subsequent code. Make sure the Callee
method completes before executing the code after it.
Asynchronous calls using Task.Run: The Callee
method is started using Task.Run
but does not wait for the result. As in case 1, the Callee
method runs in the background and the calling method continues execution immediately.
Use Task.Run and wait for the asynchronous call: The Callee
method is started using Task.Run
and wait for the result. This is equivalent to case 2, where the calling method waits for the Callee
method to complete before continuing.
Asynchronous call using Task.Run and async: Same as case 3, except that the Callee
method is declared as async
. The async
keyword allows a method to be called asynchronously even if it is wrapped by Task.Run
.
Use Task.Run and async and await the asynchronous call: Same as case 4, except the Callee
method is declared as async
. Likewise, the async
keyword allows an await method even if it is wrapped by Task.Run
.
Summary: The underlying logic of these calls is as follows:
Case 1 and 3: The Callee
method runs on a background thread and the calling method continues execution immediately.
Case 2 and 4: The calling method waits for the Callee
method to complete before executing the subsequent code.
Case 5 and 6: These are asynchronous calls using Task.Run
for additional parallel processing. However, the async
keyword allows waiting for them as needed.
The above is the detailed content of Async/Await in C#: To Await or Not to Await? The Impact on Execution. For more information, please follow other related articles on the PHP Chinese website!