我最近看到了有关如何将应用程序OnStart变成异步OnStart的建议:
protected override void OnStart()
{
this.started += onStarted; //Subscribe to event
started(this, EventArgs.Empty); //Raise event
}
protected async void onStarted(object sender, EventArgs args)
{
try
{
await // do things
}
catch (Exception ex)
{
var ignore = ex;
}
this.started -= onStarted;
}
任何人都可以看到与此相关的任何可能的问题,如果不能,那么可以将类似的内容应用于OnAppearing,如果可以,则需要进行任何更改。
最佳答案
OnAppearing
只是Page类上的void
方法
Xamarin.Forms.Page
//...
protected virtual void OnAppearing()
{
}
//...
Source
这就是Page生命周期的一部分。
//...
[EditorBrowsable(EditorBrowsableState.Never)]
public void SendAppearing()
{
if (_hasAppeared)
return;
_hasAppeared = true;
if (IsBusy)
{
if (IsPlatformEnabled)
MessagingCenter.Send(this, BusySetSignalName, true);
else
_pendingActions.Add(() => MessagingCenter.Send(this, BusySetSignalName, true));
}
OnAppearing(); //<---
Appearing?.Invoke(this, EventArgs.Empty); //NOTE HOW ACTUAL EVENT IS RAISED AFTER
var pageContainer = this as IPageContainer<Page>;
pageContainer?.CurrentPage?.SendAppearing();
FindApplication(this)?.OnPageAppearing(this);
}
//...
Source
不能将它们误认为事件处理程序,这是允许使用
async void
的一个异常(exception)。引用Async/Await - Best Practices in Asynchronous Programming
OnStart
示例中显示的方法也可以应用于OnAppearing
例如
public partial class SomePage : ContentPage {
public SomelPage() {
InitializeComponent();
appearing += onAppearing;
}
protected override void OnAppearing() {
appearing(this, EventArgs.Empty);
appearing -= onAppearing;
}
event EventHandler appearing = delegate { };
private async void onAppearing(object sender, EventArgs args) {
try {
var locator = CrossGeolocator.Current;
var position = await locator.GetPositionAsync();
var places = await SomeService.getPlacesOfInterest(position.Latitude, position.Longitude);
placesListView.ItemsSource = places;
} catch( Exception ex) {
//handler error (Log?)
}
}
}
或者,您可以直接订阅实际
Appearing
事件//...
public event EventHandler Appearing;
//...
Source
并放弃覆盖
OnAppearing()
方法public partial class SomePage : ContentPage {
public SomelPage() {
InitializeComponent();
Appearing += onAppearing;
}
private async void onAppearing(object sender, EventArgs args) {
try {
var locator = CrossGeolocator.Current;
var position = await locator.GetPositionAsync();
var places = await SomeService.getPlacesOfInterest(position.Latitude, position.Longitude);
placesListView.ItemsSource = places;
} catch( Exception ex) {
//handler error (Log?)
}
}
}