当我的应用程序启动时,如何在我的 Xamarin Forms 中调用此异步方法?

How can I call this async method in my Xamarin Forms when my app starts?

当我的应用程序第一次启动时,我需要加载一些以前保存的数据。如果它存在 -> 然后转到 TabbedPage 页面。否则,登录页面。

我不确定如何在应用程序的 ctor 或其他方法中调用我的异步方法?我该怎么做?

这是我的代码..

namespace Foo
{
    public class App : Application
    {
        public App()
        {
            Page page;

            LoadStorageDataAsync(); // TODO: HALP!

            if (Account != null)
            {
                // Lets show the dashboard.
                page = new DashboardPage();
            }
            else
            {
                // We need to login to figure out who we are.
                page = CreateAuthenticationPage();
            }

            MainPage = page;
        }

  ... snip ...
}

那么为什么 LoadStorageDataAsync 是异步的?因为它是 using the library PCLStorage 并且都是异步的。

As far as the docs say,您有可以覆盖的 Application.OnStart 事件:

Application developers override this method to perform actions when the application starts.

您可以在实际等待的地方执行您的 async 方法:

public override async void OnStart()
{
    await LoadStorageDataAsync();
}

构造函数不能是 async,但事件处理程序可以。如果可以的话,您应该将该逻辑移至 OnStart 事件处理程序(或更合适的事件处理程序):

public override async void OnStart (EventArgs e)
{
    // stuff
    await LoadStorageDataAsync();
    // stuff
}

如果不能,没有比简单地同步阻塞该任务以获得结果更好的选择了。你应该知道这可能会导致死锁。

退后一步,想想 UI 是如何工作的。当您的应用程序最初显示时,框架会构建您的 ViewModel 和 View,然后 立即(尽快)显示一些内容。那是网络 activity.

不合适的地方

相反,您应该做的是 启动 异步操作,然后(同步)加载并显示 "loading" 页面。异步操作完成后,您可以转换到其他页面(或者如果用户没有网络访问权限,则转换到 "error" 页面)。

我不确定 Xamarin Forms 是否能够将数据绑定到页面对象,但如果是,那么我的 NotifyTaskCompletion type 可能会有所帮助。

在构造函数中使用异步方法被认为是错误的代码。您不应在 class 构造函数中使用异步方法。

您可以尝试更改它以避免死锁:

Func<Task> task = async () => { 
    await YourCustomMethodAsync().ConfigureAwait(false); 
};
task().Wait();

...但我不会推荐它。