如何在await方法中处理事件提升以管理Windows商店应用程序中的ProgressBar?

时间:2016-04-14 04:24:35

标签: c# asynchronous windows-store-apps

我想在方法调用时显示进度条。我按照此票证中的建议处理了它: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完成。但它不会等待这个事件,并继续下一次执行。

有人可以建议我如何处理当前等待通话的事件?

1 个答案:

答案 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_SelectionChangedinitializeThePage完成执行时消失。