Contrary to common misconceptions, async/await doesn't create new threads. Instead, it employs cooperative multitasking to significantly improve application responsiveness.
How Async/Await Works
The compiler cleverly divides methods using async/await into two sections:
await
keyword, including the initiation of asynchronous operations.await
keyword.Execution Sequence:
await
statement. The asynchronous operation (e.g., GetSomethingAsync()
) is called. This operation returns a pending result (like a Task
).SynchronizationContext
is informed to signal completion of the asynchronous operation. Control returns to the message loop, allowing it to process other tasks.SynchronizationContext
receives a notification.SynchronizationContext
adds a message to the message loop queue, triggering the execution of Part 2. The message loop processes this, restarting the method from the point after the await
.Improved Responsiveness
While the asynchronous operation is pending, the message loop remains free to handle user input and UI updates, keeping the application responsive. Upon completion, Part 2 updates the application state.
Important Considerations:
SynchronizationContext
, not thread creation.Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3