async
await
In C#,
and are powerful keywords. They enhance the readability of the code and promote the execution of asynchronous tasks. Using them is not the same as creating background threads, because they use a different mechanism called asynchronous state machine. async
await
Example code details
Let's analyze the code fragments provided to demonstrate the work method of and
:
async
await
Behavioral explanation
private async void button1_Click(object sender, EventArgs e) { Task<int> access = DoSomethingAsync(); // 此处执行与任务无关的逻辑 int a = 1; // 立即执行,因为它不依赖于 DoSomethingAsync() int x = await access; // 等待 DoSomethingAsync() 完成 } async Task<int> DoSomethingAsync() { await Task.Delay(5000); // 使线程休眠 5 秒 return 1; }
The method is marked as to enable its asynchronous execution.
button1_Click
When running in the background, you can perform independent logic. async
DoSomethingAsync()
is completed. DoSomethingAsync()
to await access;
button1_Click
DoSomethingAsync()
and DoSomethingAsync()
await
When using and x
, the compiler generates an asynchronous state machine. The mounting and recovery of this state machine management task allows asynchronous operations to write and perform asynchronous operations in a simplified manner.
async
await
Improving code readability
async
Enhanced UI's response ability await
The above is the detailed content of When and How Should You Use Async and Await in C#?. For more information, please follow other related articles on the PHP Chinese website!