Xamarin Async method usage OnStart()

北慕城南 提交于 2021-02-20 14:50:33

问题


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

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