问题
Trying to address the following issue :
To provide a progress indicator that will be shown until the navigation target finishes loading. The target being navigated to can take up to 30 seconds for loading as there are images being fetched from different sources on the Internet.
Problem lies on handling such task using events of NavigationService or Page as they are always raised before the Page has loaded its content which is done inside the Loaded event. The loading process is asynchronous for not blocking UI and as such, cannot be moved to the constructor as it cannot be marked as async.
Is there an efficient pattern for addressing such problem ?
回答1:
One option here is to have the constructor create a method that returns a Task<T>, and then store this in a class member.
Your Loaded event can then use await on the created task to extract out the data and display it asynchronously.
This will look something like:
Task<YourData> initialDataLoadTask;
// In your constructor:
YourPage()
{
this.InitializeComponent();
// Use async method here to fetch data, but do NOT use await
this.initialDataLoadTask = FetchDataAsync();
this.Loaded += this.OnLoaded;
}
private async void OnLoaded(object sender, RoutedEventArgs e)
{
// Use await to pull out the data asynchronously now...
var data = await this.initialDataLoadTask;
// Display data as needed...
}
This allows the entire chain to be asynchronous, with the constructor still initializing the fetch of the data (so it comes in as fast as possible).
来源:https://stackoverflow.com/questions/17279735/which-strategy-to-employ-for-long-to-load-pages