简体   繁体   中英

How can i wait an async method to finish and then continue executing an instruction?

I am creating a cross platform app on xamarin.forms. I'm using a plugin to display a popup window. However, it seems like the await key is not working since the execution continues before the task is completed. Besided that, if the button to display a popup is clicked fast many times consecutively, the popup will be displayed this many times clicked instead of displaying once and block all the rest.

I have a command attached to a button. Whenever the button is clicked, the command property is fired corectly but the await seems to have no effect.

public ICommand {
            get => new Command(async () =>
            {
                if (ObjectivosDoMes.Count < 3)
                    await PopupNavigation.Instance.PushAsync(new NovoObjectivoDoMes(ObjectivosDoMes), true);
                        PodeAdicionarObjMes = ObjectivosDoMes.Count < 3 ? true : false;
            });
        }

I would like to the code after popup being displayed to be execute just after the popup is closed. This is the library i am using to display popup : https://github.com/rotorgames/Rg.Plugins.Popup

Within your code you are making the assumption that the task returned by PopupNavigation will finish when the popup is closed. Instead, once the popup page has been pushed to the navigation stack this task will finish. So awaiting this task will not be helpful to detect when the popup has been closed. You could hook into the Disappearing event of the popup page. Here is some working example that is self contained and does not depend on other Views/ViewModels.

       // in constructor
        ButtonTappedCommand = new Command(async () => await OnButtonTappedCommand()) ;
        page = new Rg.Plugins.Popup.Pages.PopupPage();
    }

    private async Task OnButtonTappedCommand()
    {
        page.Content = new Button() 
        { 
           Text="Close", 
           // close the popup page on tap
           Command = new Command(()=>PopupNavigation.Instance.PopAsync()) 
        };
        page.Disappearing += Popup_Disappearing;

        await PopupNavigation.Instance.PushAsync(page);
    }

    private void Popup_Disappearing(object sender, EventArgs e)
    {
        page.Disappearing -= Popup_Disappearing;
        Debug.WriteLine("Someone closed the popup");
    }

await is working fine. The popup library you're using completes its PushAsync operation when the popup is shown , not when it is closed . See this issue for a workaround that allows you to await the popup being closed.

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