您好我无法弄清楚为什么这种异步操作不会等待
private async void scroller_ViewChanged(object sender, ScrollViewerViewChangedEventArgs e)
{
if (isLoadingMore)
return;
if (scroller.VerticalOffset > scrollContent.ActualHeight - (Frame.ActualHeight + 300))
await LoadMoreItems();
}
bool isLoadingMore = false;
private async Task LoadMoreItems()
{
isLoadingMore = true;
try
{
List<Items> itemsList = await App.ServiceClient.GetItems("bananas");//<-------Doesn't wait
foreach (Items in itemsList)
listView.Items.Add(c);
}
catch { }
isLoadingMore = false;
}
这是另一个异步任务的后端调用
public async Task<List<Items>> GetItems(string selector)
{
HttpClient client = new HttpClient();
var request = new HttpRequestMessage()
{
RequestUri = new Uri(myUrl),
Method = HttpMethod.Get,
};
request.Headers.Add("Accept", "application/json");
List<Items> items = null;
var task = await client.SendAsync(request).ContinueWith(
async (s) =>
{
try
{
string Result = await s.Result.Content.ReadAsStringAsync();
if (s.Result.IsSuccessStatusCode)
items= JsonConvert.DeserializeObject<List<Items>>(Result);
}
catch
{ }
});
return items;
}
问题是嵌套等待或在scoll视图中。 我发现this但我不认为情况就是这样。
答案 0 :(得分:1)
事件处理程序为async void
,因此用户界面永远不会等待这一点,如果您无法处理多个ViewChanged
事件,则有两个选项:
1 - 在执行异步调用时禁用滚动条:
private async void scroller_ViewChanged(object sender, ScrollViewerViewChangedEventArgs e)
{
scroller.Enabled = false;
try
{
if (isLoadingMore)
return;
if (scroller.VerticalOffset > scrollContent.ActualHeight - (Frame.ActualHeight + 300))
await LoadMoreItems();
}
finally{ scroller.Enabled = true; }
}
如果还有另一个事件处理程序正在运行,那么不要执行代码:
bool runnning = false
private async void scroller_ViewChanged(object sender, ScrollViewerViewChangedEventArgs e)
{
if(running)
return;
runnning = true;
try
{
if (isLoadingMore)
return;
if (scroller.VerticalOffset > scrollContent.ActualHeight - (Frame.ActualHeight + 300))
await LoadMoreItems();
}
finally{ running = false; }
}