await and Navigation.PushAsync()

GerryIgnatiusGerryIgnatius USMember, University

Hello,
I want to do something like that:
1. User clicks on "New Thing" button. Navigation.PushAsync is called.
2. User enters some data and clicks "Submit" on New thing page. Navigation.PopAsync is called.
3. Code grabs data from page and something makes with it.

var toolbarItem = new ToolbarItem {
                Text = "New",
            };
            toolbarItem.Clicked += async delegate {
                var page = new NewThingPage ();
                await Navigation.PushAsync (page);  
                Debug.WriteLine ("**It should be called only after return from NewThingPage, but it always called before it. Why?**");
            };
            this.ToolbarItems.Add (toolbarItem);

Can somebody explain me why thread doesn't suspend execution at line with "await Navigation.PushAsync (page);"

Answers

  • AdamPAdamP AUUniversity ✭✭✭✭✭

    @GerryIgnatius - How are you determining that the code isn't run after the PushAsync.

    The PushAsync will push the object onto the navigations stack, then the platform will show the new page. But I think the fact of showing the new page isn't awaited that goes off on another thread.

    I will just go check what Xamarin actually does behind the scenes on that one.

  • AdamPAdamP AUUniversity ✭✭✭✭✭
    edited October 2015

    To add to my answer here is what happens.

    A PushAsync adds it to the NavigationStack, then an event called Pushed is raised. The Pushed event will then be picked up elsewhere and the actual showing of a new page will occur.

    But when you are awaiting a PushAsync, it is only awaiting the fact of it being added to the stack, not the page being shown by the platform.

    So the CurrentPage property will be updated, but things like the OnAppearing event in the page might not yet have been triggered.

  • Thanks Adam.
    I guess the best way is passing anonimous delegate to new NewThingPage() and calls this delegate when user clicks "submit" button .

    var toolbarItem = new ToolbarItem {
                    Text = "New",
                };
                toolbarItem.Clicked += async delegate {
                    var page = new NewThingPage (Func<>{Debug.WriteLine("**This code will be executed when user clicks submit button. For example: Grabbing data and storing new items to database**")});
                    await Navigation.PushAsync (page);  
                };
                this.ToolbarItems.Add (toolbarItem);
    
Sign In or Register to comment.