In the asynchronous programming
and understanding async
await
Many developers are confused about the work mechanism of
in asynchronous programming. To understand the mystery of their usage, we will explore their mechanisms and show the difference between them and generate background threads. async
await
Clarifying
Usage async
await
Your example emphasizes the use of and
async
In your code, after starting "DOSOMETHINGASYNC ()", the code continues to perform operations that are not related to the task. The "Access" variable holds the task that will end up. When reaching the "AWAIT Access" statement, the code is suspended and released the current thread. await
async
Understand the background execution
In contrast to your assumptions, "DOSOMETHINGASYNC ()" will not be executed on the background thread. It uses the current thread and starts the dormant operation. After completion, the state machine resumes execution and allows continuing to continue executing "Button1_CLICK".
A more comprehensive asynchronous example
In order to provide a clearer understanding, please consider the following example examples:
In this scene:
"MyMethodasync ()" starts "LongruningOperationasync ()".
<code class="language-csharp">public async Task MyMethodAsync() { Task<int> longRunningTask = LongRunningOperationAsync(); // 这里可以进行独立的工作... // 等待长时间运行的任务 int result = await longRunningTask; // 使用结果... } public async Task<int> LongRunningOperationAsync() { await Task.Delay(1000); // 1秒延迟 return 1; }</code>
When encountering "AWait Longrunningtask", the main thread will release and execute the suspension.
The above is the detailed content of How Do `async` and `await` Work in Async Programming Without Spawning Background Threads?. For more information, please follow other related articles on the PHP Chinese website!