Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# (Xamarin) "async void" in framework override

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?

like image 391
Betty Crokker Avatar asked Feb 04 '23 22:02

Betty Crokker


1 Answers

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

like image 98
Jon Douglas Avatar answered Feb 08 '23 15:02

Jon Douglas