0

我是 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);

        }
    }
}

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

4

1 回答 1

2

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

您还应该将 UI loginc 从非 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

于 2014-08-12T11:48:58.777 回答