Thought
Thought

Reputation: 5846

await on windows store app, not working as expected

on a windows store project im working on i have this piece of code on the app.xaml.cs file

    ...          
            DoStuff();



                // Place the frame in the current Window
                Window.Current.Content = rootFrame;
            }
            if (rootFrame.Content == null)
            {
                // When the navigation stack isn't restored navigate to the first page,
                // configuring the new page by passing required information as a navigation
                // parameter
                rootFrame.Navigate(typeof(SomePage), e.Arguments);
            }

and on the DoStuff function after some operations, i call this other function called InsertDB.

    private async void InsertDB(RootObject obj)
    {
        await Task.Run(() => obj.InsereDB());
    }

What this one does , is insert some data into a sqlite database. Now my problem is this, when i start my app the database starts getting filled, i can see that cause im looking at the file inside the LocalState folder of my project, and the sqlite file starts growing in size, but before it finishes getting the data inside my View("SomePage") gets loaded.

Shouldn't the await task prevent the view from loading until the "obj.InsereDB" function returns ?

Upvotes: 0

Views: 77

Answers (1)

dcastro
dcastro

Reputation: 68640

It's not waiting because InsertDB is an async void method, which means, from the caller's perspective, it will run synchronously until it hits the first await keyword. Once it does, it will return to the caller.

Picture this:

private async void InsertDB(RootObject obj)
{
    Console.WriteLine(1);
    await Task.Run(() => obj.InsereDB());
    Console.WriteLine(2);
}

InsertDB(obj);
Console.WriteLine(3);

This code will print 1 3 2. When InsertDB hit the await keyword, it returned to the caller, which printed 3. The rest of the method ran asynchronously.

You need to make InsertDB return a task, and await it.

private async Task InsertDB(RootObject obj)
{
    Console.WriteLine(1);
    await Task.Run(() => obj.InsereDB());
    Console.WriteLine(2);
}

await InsertDB(obj);
Console.WriteLine(3);

This will print 1 2 3

Upvotes: 2

Related Questions