ProgressIndicator在async函数中没有准确显示



我是WP的新手。我试图显示ProgressIndicator时,从服务器加载数据,并在加载完成时隐藏它。然而,我有一个问题:"ProgressIndicator只显示当我的MessageBox显示。下面是我的代码:

    private void MainPageLoaded(object sender, RoutedEventArgs e)
    {
        // Create progress loading 
        SystemTray.ProgressIndicator = new ProgressIndicator();
        SystemTray.ProgressIndicator.IsIndeterminate = true;
        SystemTray.ProgressIndicator.IsIndeterminate = true;
        SystemTray.ProgressIndicator.Text = "Loading...";
        SyncDbIfNeed();
    }

    private void ShowHideProgressIndicator(Boolean isVisible)
    {
        SystemTray.ProgressIndicator.IsVisible = isVisible;
        SystemTray.ProgressIndicator.IsIndeterminate = isVisible;
        Debug.WriteLine("ShowHide: " + isVisible);
    }

    private async void SyncDbIfNeed()
    {
        if (!MySettings.IsCategorySynced())
        {
            ShowHideProgressIndicator(true);
            try
            {
                HttpClient httpClient = new HttpClient();
                String json = await httpClient.GetStringAsync(MyConstants.UrlGetAllCategory);
                MessageBox.Show(json);
            }
            catch (Exception e)
            {
                MessageBox.Show("Unexpected error");
            }
            ShowHideProgressIndicator(false);
        }
    }
}

谁能解释一下,给我一个建议?谢谢。

async void方法应该只用于事件处理程序。任何其他异步方法应该返回TaskTask<T>

你还应该将UI登录从非UI逻辑中分离出来。

试试这个:

private async void MainPageLoaded(object sender, RoutedEventArgs e)
{
    SystemTray.ProgressIndicator = new ProgressIndicator();
    SystemTray.ProgressIndicator.IsIndeterminate = true;
    SystemTray.ProgressIndicator.Text = "Loading...";
    ShowHideProgressIndicator(true);
    try
    {
        var json = await SyncDbIfNeedAsync();
    }
    catch (Exception e)
    {
        MessageBox.Show("Unexpected error");
    }
    ShowHideProgressIndicator(false);
}
private void ShowHideProgressIndicator(Boolean isVisible)
{
    SystemTray.ProgressIndicator.IsVisible = isVisible;
    SystemTray.ProgressIndicator.IsIndeterminate = isVisible;
    Debug.WriteLine("ShowHide: " + isVisible);
}

private async Task<string> SyncDbIfNeedAsync()
{
    if (!MySettings.IsCategorySynced())
    {
        HttpClient httpClient = new HttpClient();
        return await httpClient.GetStringAsync(MyConstants.UrlGetAllCategory);
        MessageBox.Show(json);
    }
}

要了解更多关于async - await的信息,请查看我的curah

相关内容

  • 没有找到相关文章

最新更新