问题
Is it considered a good practice to call an Async
method that does some heavy lifting with server connections and data exchange during OnStart()
event of the application given that this method does not touch the UI thread? Are all the components of the application properly initialized at the time of this event firing for the Async
method to be able to execute?
protected override async void OnStart()
{
sendHttpRequestAsync();
}
private async void sendHttpRequestAsync() {
await ...
}
回答1:
Avoid using async void
on anything except event handlers.
Reference Async/Await - Best Practices in Asynchronous Programming
OnStart however is not an event handler. Just a regular method that according to documentation...
Application developers override this method to perform actions when the application starts.
As a work around you can create your own custom event and handler that will allow for an async void
to be performed on your event handler. You will subscribe to the event when OnStart
is invoked by the application and then raise the custom event to be handled asynchronously. sendHttpRequestAsync()
would need to be refactored to return a Task
so that it can be awaited safely.
//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 ...
}
来源:https://stackoverflow.com/questions/48957339/xamarin-async-method-usage-onstart