页面显示时,我有一个需要运行的功能。这是下面的代码:
protected async override void OnAppearing()
{
LeaveViewModel lvm = new LeaveViewModel();
await lvm.FetchingAsync();
}
public ICommand LeaveCommand
{
get
{
return new Command(async () => await FetchingAsync());
}
}
public async Task FetchingAsync()
{
await _apiServices.FetchLeave(this);
}
public async Task FetchLeave(LeaveViewModel lvm)
{
var keyValues = new List<KeyValuePair<string, string>>
{
new KeyValuePair<string, string>("UserID",App._username),
};
var request = new HttpRequestMessage(HttpMethod.Post, "somelink");
request.Content = new FormUrlEncodedContent(keyValues);
var client = new HttpClient();
var response = await client.SendAsync(request);
var content = await response.Content.ReadAsStringAsync();
Debug.WriteLine(content);
if (content == "[]")
{
await App.Current.MainPage.DisplayAlert("Error", "No data recorded!", "OK");
}
else
{
var posts = JsonConvert.DeserializeObject<List<LeaveViewModel>>(content);
lvm.ViewList = new List<LeaveViewModel>(posts);
}
}
当我调试代码并到达
var response = await client.SendAsync(request);
调试器返回到FetchingAsync()函数,在var响应后完全跳过其余代码。 当我在按钮而不是OnAppearing()中运行代码并将按钮绑定到Icommand时,整个代码将得到完美处理。但是我需要在页面加载时显示数据,而不是在单击按钮时显示数据。 我读到这是由于异步/等待引起的,但是我对此并不陌生,我不明白这是怎么回事。 我该如何实现?我在做什么错?