Xamarin异步方法的用法OnStart() [英] Xamarin Async method usage OnStart()

查看:95
本文介绍了Xamarin异步方法的用法OnStart()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

 受保护的重写异步void OnStart(){sendHttpRequestAsync();}私人异步void sendHttpRequestAsync(){等待...} 

解决方案

除事件处理程序外,请勿在其他任何代码上使用 async void .

参考异步/等待-异步编程的最佳做法

OnStart 但是不是事件处理程序.只是根据文档的常规方法...

应用程序开发人员将覆盖此方法,以在应用程序启动时执行操作.

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

 //启动应用程序时引发的自定义事件私有事件EventHandler起始=委托{};//应用程序开发人员重写此方法//在应用程序启动时执行操作.受保护的重写void OnStart(){//订阅活动开始+ = onStarting;//筹款活动开始(这是EventArgs.Empty);}私人异步void onStarting(对象发送者,EventArgs args){//取消订阅活动正在启动-= onStarting;//执行非阻塞动作等待sendHttpRequestAsync();}私人异步任务sendHttpRequestAsync(){等待...} 

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

解决方案

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

这篇关于Xamarin异步方法的用法OnStart()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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