我想在方法调用时显示进度条。我按照此票证中的建议处理了它:ProgressBar button doesn't show while service call in windows store app
它不会等待当前事件内部引发的事件。 即
public async void navigationHelper_LoadState(object sender, LoadStateEventArgs e)
{
loading.Visibility = Windows.UI.Xaml.Visibility.Visible;
await initializeThePage();
loading.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
}
//following method doesn't wait for SelectionChanged event. It should wait
private async Task initializeThePage()
{
//few service call here
cmdStore.SelectedIndex = 1; //this should wait until cmdStore_SelectionChanged complete its call
}
private async void cmdStore_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
//few service call here
loading.Visibility = Windows.UI.Xaml.Visibility.Visible;
await getOrderlistAccordingToStore(storeID); //get store details
loading.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
}
public async Task getOrderlistAccordingToStore(int storeID)
{
//calls of get orderlist according to selected store
}
当cmdStore.SelectedIndex = 1;
调用时,它会调用cmdStore_SelectionChanged
方法。在这种情况下,await initializeThePage();
应该等到cmdStore_SelectionChanged
完成。但它不会等待这个事件,并继续下一次执行。
有人可以建议我如何处理当前等待通话的事件?
答案 0 :(得分:1)
cmdStore_SelectionChanged
绑定到事件处理程序并且为async void
。您无法直接等待此方法的执行完成
你可以做一些解决方法来处理它。首先介绍帮助方法来显示/隐藏加载器。
int waitCounter = 0;
void ShowLoader()
{
waitCounter += 1;
if (waitCounter > 1) // Already loader is visible
return;
loading.Visibility = Windows.UI.Xaml.Visibility.Visible;
}
void HideLoader()
{
waitCounter -= 1;
if (waitCounter <= 0) // No more call to wait for
loading.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
}
之后修改您的实现看起来像这样
public async void navigationHelper_LoadState(object sender, LoadStateEventArgs e)
{
ShowLoader()
await initializeThePage();
HideLoader()
}
private async Task initializeThePage()
{
//few service call here
cmdStore.SelectedIndex = 1;
}
private async void cmdStore_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
ShowLoader();
//few service call here
await getOrderlistAccordingToStore(storeID); //get store details
HideLoader();
}
public async Task getOrderlistAccordingToStore(int storeID)
{
//calls of get orderlist according to selected store
}
首次初始化页面时,加载程序将可见,并在cmdStore_SelectionChanged
和initializeThePage
完成执行时消失。