I have a screen that retrieves information from a remote server and displays that information to the user. I would like this information to be updated when the screen is displayed (requiring no additional user interaction).
public partial class MyPage : ContentPage
{
protected override async void OnAppearing()
{
base.OnAppearing();
try
{
MyLabel.Text = (await GoGetTheData ()).Stuff;
}
catch (Exception e)
{
MyLabel.Text = "Narg";
}
}
}
Is this acceptable? I've seen all the discussions about the evils of "async void", and how it should only be used in event handlers, and this isn't quite an event handler.
Is the framework guaranteed to be OK in this case, since I (1) called base.OnAppearing() before getting all asynchronous, and (2) caught my exceptions?
This is acceptable. Support for async on these framework overrides were added for a reason. There are evils of "async void" in general, but this case doesn't apply.
One note however is that you should ensure that your OnAppearing(Forms)
, OnCreate(Android)
, and ViewDidLoad(iOS)
methods return as soon as possible so your users have a pleasant experience.
In fact you will see this exact syntax in plenty of Forms samples: https://github.com/xamarin/xamarin-forms-samples/search?utf8=%E2%9C%93&q=async+void+OnAppearing
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With