Richard Scholey
Richard Scholey

Reputation: 83

Can an async method override a method in a base class that's not async in Xamarin Forms?

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?

Upvotes: 1

Views: 795

Answers (1)

Stephen Cleary
Stephen Cleary

Reputation: 457057

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.

Upvotes: 1

Related Questions