我是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
方法应该只用于事件处理程序。任何其他异步方法应该返回Task
或Task<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