在我的項目中,我想顯示一個進度指示器,從web服務中檢索數據並隱藏進度指示器。如果我這樣做,我現在不得不等待,直到從Web服務檢索到數據,然後用戶界面的結果立即更新。但進度指標從未出現。所以看來,我在UI線程上工作或阻塞。但是哪裏?直到異步方法完成後UI纔會更新
這是我的一個簡單的代碼版本:
SomePage的
private async void OnItemSelected(object sender, SelectedItemChangedEventArgs e)
{
await ShowDetailView();
}
private async Task ShowDetailView()
{
var view = new MyView();
this.detailView = view;
await view.LoadContent();
}
SomeView
public async Task LoadContent()
{
var success = await LoadData();
if (success)
{
ShowInformation();
}
}
public async Task<bool> LoadData()
{
try
{
ShowLoadingProcess();
await Task.Delay(5000);
this.itemList = await WebService.Instance.GetData();
return true;
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine(ex.Message);
return false;
}
finally
{
HideLoadingProcess();
}
}
private void ShowInformation()
{
Device.BeginInvokeOnMainThread(() =>
{
this.grid.Clear();
foreach(var item in this.itemList)
{
GridItem contentItem = new GridItem(item);
this.grid.Children.Add(contentItem);
}
}
}
private void ShowLoadingProcess()
{
Device.BeginInvokeOnMainThread(() => BringProgressIndicatorToFront());
}
private void HideLoadingProcess()
{
Device.BeginInvokeOnMainThread(() => BringProgressIndicatorToBack());
}
我嘗試不同的東西,在這裏我之間有不同步UI和後臺線程。例如。在LoadData()
完成之前調用ShowInformation()
。
有人可以給我提示這裏有什麼問題嗎?
您正在查找[BackgroundWorker](https://developer.xamarin.com/api/type/System.ComponentModel.BackgroundWorker/)。這使您可以運行異步任務並從中報告進度。 –
@LukeSamuel如果您正確使用TPL,則不需要BGW。 – Servy