async和等待:簡化異步編程而不阻止UI
async
和await
是異步編程的強大工具,可改善代碼的可讀性和可維護性。 但是,它們的操作與傳統背景線程有很大不同。讓我們澄清他們的行為。
考慮此代碼:
<code class="language-csharp">private async void button1_Click(object sender, EventArgs e) { Task<int> access = DoSomethingAsync(); // Other UI-responsive tasks here int a = 1; // This executes immediately, not after the 5-second delay int x = await access; // Execution pauses here until DoSomethingAsync completes }</code>
async
關鍵字向編譯器發出信號以生成狀態計算機。該機器管理異步操作的生命週期。 access
>啟動異步任務(DoSomethingAsync
)。 至關重要的是,因為DoSomethingAsync
使用await
,所以button1_Click
方法不會阻止UI線程。 // Other UI-responsive tasks here
段可以同時執行。
DoSomethingAsync
(未顯示,但假定包含System.Threading.Thread.Sleep(5000)
)引入了5秒的延遲。 但是,await access
將控制回到呼叫者。 UI保持響應能力。 完成DoSomethingAsync
>完成時,線程池線程從關閉的位置恢復button1_Click
,將結果分配給x
>。
,Thread.Start()
和async
不創建新線程。相反,它們利用線程池和狀態機有效地管理異步操作,防止UI凍結並啟用並發執行。 這為異步編程提供了一種更清潔,更高效的方法。 await
>
以上是``Async'和`等待如何在不阻止UI線程的情況下管理異步操作?的詳細內容。更多資訊請關注PHP中文網其他相關文章!