ProgressIndicator doesnt showed exactly in async function

111 Views Asked by At

I'm new to WP. I try to show ProgressIndicator when loading data from Server and hide it when loading finished. However, I had a problem: "The ProgressIndicator only show when my MessageBox showed. Here's my code:

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

        }
    }
}

Can anyone explain it, and give me an advice? Thanks.

1

There are 1 best solutions below

1
On

async void methods should only be used for event handlers. Any other asynchronous method should return a Task or Task<T>.

You should also split UI loginc from non-UI logic.

Try this instead:

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);
    }
}

To learn more about async-await, take a look at my curah.