Xamarin Forms await is not respected

Asked

Viewed 113 times

6

Good night,

someone can tell me why the code below does not respect Wait, in debug the exit order is

    1. init save
    2. End Save 3. New header ID: 1

instead of:

    1. init save
    2. New header ID: 1
    3. End Save
public async Task Save(Ticket header, TicketLines newLines)
{
                Debug.WriteLine("init save");
                await dbConnection.RunInTransactionAsync(new Action<SQLite.Net.SQLiteConnection>(tran =>
                {
                    dbConnection.InsertAsync(header).ContinueWith((t) =>
                    {
                        Debug.WriteLine("New header ID: {0}", header.Id);                       
                        foreach (var item in newLines)
                        {
                            item.DocumentId = header.Id;
                        }
                        dbConnection.InsertAllAsync(newLines);                     
                    });
                    //tran.Commit();                    
                }));
                Debug.WriteLine("End Save");

}

I want to call the metodo Save and at the end I refresh the screen, what happens as it does not respect the Await I have refresh the screen and still do not enter the data

1 answer

1

In fact, what’s happening is that you’re not expecting the function InsertAsync, then program follows the normal flow and prints End Save, as expected.

The output you want requires the call to InsertAsync has ended, and ContinueWith has started. For this, just insert a await before dbConnection.InsertAsync. With this, the execution of this method will be stopped until ContinueWith be completed.

Heed: dbConnection.InsertAsync(...).ContinueWith(...) returns a awaitable referring to the call ContinueWith, and not InserAsync.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.