簡體   English   中英

Xamarin async OnStart() 表現不同?

[英]Xamarin async OnStart() behaving differently?

在我的應用程序 class 中,我有以下代碼,可以正常工作

    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();
    }

Initialise() 例程從手機本地文件系統讀取配置文件並設置主題。

我想我會整理一下並將其更改為:

    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();
    }

調試似乎表明相同的代碼以相同的順序執行。 但是,我的 MainPage 沒有顯示???

有沒有人知道為什么第二個代碼塊與第一個代碼塊的工作方式不同?

非事件處理程序上的async void是這里的問題。

OnStart不是事件處理程序,將被區別對待,因為它將在單獨的線程上作為觸發並忘記調用執行。

以下重構將按預期工作。

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();
}

參考Async/Await - 異步編程的最佳實踐

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM