Which strategy to employ for long to load pages?

女生的网名这么多〃 提交于 2020-02-05 03:24:46

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!