长时间采用哪种策略来加载页面? [英] Which strategy to employ for long to load pages?

查看:53
本文介绍了长时间采用哪种策略来加载页面?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

试图解决以下问题:

提供进度指示器,该指示器将一直显示到导航目标完成加载为止.导航到的目标最多可能需要30秒钟才能加载,因为有图像是从Internet上的不同来源获取的.

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.

问题在于使用 NavigationService Page ,因为它们总是 在Page加载其内容之前引发的strong>,该内容在Loaded事件内完成.加载过程是异步的,因为它不会阻止UI,因此,由于无法将其标记为异步,因此无法将其移至构造函数.

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 ?

推荐答案

这里的一个选择是让构造函数创建一个返回Task<T>的方法,然后将其存储在类成员中

One option here is to have the constructor create a method that returns a Task<T>, and then store this in a class member.

然后,您的Loaded事件可以在创建的任务上使用await提取数据并异步显示.

Your Loaded event can then use await on the created task to extract out the data and display it asynchronously.

这看起来像:

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

这篇关于长时间采用哪种策略来加载页面?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆