C# MAUI await async 函數 用法
C# MAUI await async 函數 用法
Copilot Code:
using System.Net.Http;
using Microsoft.Maui.Controls;
public partial class MainPage : ContentPage
{
public MainPage()
{
InitializeComponent();
}
private async void OnButtonClicked(object sender, EventArgs e)
{
string result = await FetchDataAsync("https://example.com");
// 在這裡處理獲取到的數據
DisplayAlert("Data", result, "OK");
}
private async Task<string> FetchDataAsync(string url)
{
using (HttpClient client = new HttpClient())
{
HttpResponseMessage response = await client.GetAsync(url);
response.EnsureSuccessStatusCode();
string responseBody = await response.Content.ReadAsStringAsync();
return responseBody;
}
}
}
Copilot 說明:
01.FetchDataAsync 方法是一個非同步方法,使用 async 關鍵字定義,並返回一個 Task<string>。
02.在 FetchDataAsync 方法內部,使用 await 關鍵字等待 HttpClient.GetAsync 和 HttpContent.ReadAsStringAsync 方法完成。
03.OnButtonClicked 方法也是非同步的,當按鈕被點擊時,它會呼叫 FetchDataAsync 並等待其完成。
PS.這樣的設計可以確保 UI 執行緒不會被阻塞,應用程式可以保持回應。