Xamarin异步方法的用法OnStart()

ast*_*ter 5 c# async-await xamarin

考虑到该方法不涉及UI线程,调用一种在应用程序事件Async期间对服务器连接和数据交换进行一些繁重工作的方法是否被认为是一种好习惯OnStart()?在此事件触发时,是否已正确初始化应用程序的所有组件,以使Async方法能够执行?

protected override async void OnStart()
{
    sendHttpRequestAsync();
}

private async void sendHttpRequestAsync() {
  await ...
}
Run Code Online (Sandbox Code Playgroud)

Nko*_*osi 6

避免async void在除事件处理程序之外的任何东西上使用。

参考Async/Await - 异步编程的最佳实践

OnStart然而不是事件处理程序。只是一种常规方法,根据文档...

应用程序开发人员重写此方法以在应用程序启动时执行操作。

作为一种变通方法,您可以创建自己的自定义事件和处理程序,以便async void在您的事件处理程序上执行。您将OnStart在应用程序调用时订阅该事件,然后引发要异步处理的自定义事件。sendHttpRequestAsync()需要重构以返回 aTask以便可以安全地等待它。

//Custom event that is raised when the application is starting
private event EventHandler Starting = delegate { };

//Application developers override this method  
//to perform actions when the application starts.
protected override void OnStart() {
    //subscribe to event
    Starting += onStarting;
    //raise event
    Starting(this, EventArgs.Empty);
}

private async void onStarting(object sender, EventArgs args) {
    //unsubscribe from event
    Starting -= onStarting;
    //perform non-blocking actions
    await sendHttpRequestAsync();
}

private async Task sendHttpRequestAsync() {
    await ...
}
Run Code Online (Sandbox Code Playgroud)