Home >Backend Development >C++ >Async/Await in C#: To Await or Not to Await? The Impact on Execution

Async/Await in C#: To Await or Not to Await? The Impact on Execution

Susan Sarandon
Susan SarandonOriginal
2025-01-12 13:22:43956browse

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:

  1. 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.

  2. 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.

  3. 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.

  4. 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.

  5. 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.

  6. 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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn