简体   繁体   中英

Xamarin async OnStart() behaving differently?

In my App class, I have the following code, which works fine .

    protected override void OnStart()
    {
        // Initialise the application
        var intialise = Task.Run(async () => await Initialise());
        intialise.Wait();

        // Default to the Log on screen
        if (Helper.IsPortrait)
            MainPage = new LogOnPortraitPage();
        else
            MainPage = new LogOnLandscapePage();

        base.OnStart();
    }

The Initialise() routine reads in a Config file from the phones local file system and sets a theme.

I thought I would tidy it up a bit and change it to:

    protected override async void OnStart()    // Added async
    {
        // Initialise the application
        await Initialise();                    // Changed to one line

        // Default to the Log on screen
        if (Helper.IsPortrait)
            MainPage = new LogOnPortraitPage();
        else
            MainPage = new LogOnLandscapePage();

        base.OnStart();
    }

Debugging seems to indicate that the same code is executed in the same order. However, my MainPage is not displayed???

Has anyone any idea as to why the second block of code does not work the same as the first?

async void on a non event handler is the issue here.

OnStart is not an event handler and will be treated differently as it will be executed on a separate thread as a fire and forget invocation.

The following refactor will work as expected.

private event EventHandler onStart = delegate { };

protected override void OnStart() {
    onStart += handleStart; //subscribe
    onStart(this, EventArgs.Empty); //raise event
}

private async void handleStart(object sender,EventArgs args) {
    onStart -= handleStart; //unsubscribe

    // Initialise the application
    await Initialise();

    // Default to the Log on screen
    if (Helper.IsPortrait)
        MainPage = new LogOnPortraitPage();
    else
        MainPage = new LogOnLandscapePage();

    base.OnStart();
}

Reference Async/Await - Best Practices in Asynchronous Programming

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM