1

Here's a base class that I have:

public abstract class BaseContentPage : ContentPage
{

    protected BaseContentPage(in IAnalyticsService analyticsService,
                                in IMainThread mainThread,
                                in bool shouldUseSafeArea = false)
    {
        MainThread = mainThread;
        AnalyticsService = analyticsService;

        this.DynamicResource(BackgroundColorProperty, nameof(BaseTheme.PageBackgroundColor));

        On<iOS>().SetUseSafeArea(shouldUseSafeArea);
        On<iOS>().SetModalPresentationStyle(UIModalPresentationStyle.FormSheet);
    }

    protected IAnalyticsService AnalyticsService { get; }
    protected IMainThread MainThread { get; }

    protected override void OnAppearing()
    {
        base.OnAppearing();

        AnalyticsService.Track($"{GetType().Name} Appeared");
    }

This is later used like this:

public class SplashScreenPage : BaseContentPage
{

    readonly Label _loadingLabel;
    readonly Image _gitTrendsImage;
    readonly FirstRunService _firstRunService;
    readonly AppInitializationService _appInitializationService;
    public SplashScreenPage(IMainThread mainThread,
                                FirstRunService firstRunService,
                                IAnalyticsService analyticsService,
                                AppInitializationService appInitializationService)
        : base(analyticsService, mainThread)
    {
    }

    protected override async void OnAppearing()
    {
        base.OnAppearing();
        await ChangeLabelText(_statusMessageEnumerator.Current);

My questions are I think both about the same thing:

a) Is it okay to override a non-async method with an async method when used in this way in Xamarin Forms?

b) I know Xamarin calls a normal OnAppearing but will it call an async OnAppearing in the same way?

  • async is not actually part of the method signature, so it does not impact your ability to override a base method. "OnAppearing" and "async OnAppearing" will both work – Jason Apr 03 '21 at 15:21
  • check the answer here https://stackoverflow.com/questions/35817558/why-does-c-sharp-allow-making-an-override-async – G.Mich Apr 03 '21 at 19:17

1 Answers1

1

async is an implementation detail. If you have a base method that returns Task, then you can override it with async Task whether or not the base method uses async.

This is a special case because the return type is void. In most cases, you should avoid async void. async void should really only be used for event handlers.

In this specific case (OnAppearing), the method is logically an event handler. So in this specific case, overriding with async void is probably fine. Just bear in mind that the UI will return to its message loop at each await.

Stephen Cleary
  • 437,863
  • 77
  • 675
  • 810