Async / waiting for a simple example

I am trying to understand the basics of async / await by creating a simple example. I am using Sqlite with an asynchronous connection, and I have a class like this:

public class User
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }

Now let's say that I want to save Userto my UserTable, and when the save is done, I want to get it.

public async ? SaveToDb()
        {
            _conn.CreateTableAsync<User>();
            await _conn.InsertAsync(new User(){Id=1, Name = "Bill"});

            //Code that waits for the save to complete and then retrieves the user
        }

I suspect I need a task somewhere, but I'm not quite sure how to do this. Thanks you

+4
source share
2 answers

Mostly you are already there.

Upon return void:

public async Task SomethingAsync()
{
    await DoSomethingAsync();
}

When returning the result:

public async Task<string> SomethingAsync()
{
    return await DoSomethingAsync();
}

It should be noted that when you return the values ​​in the async method, you return the internal type (i.e. in this case string), and not the instance Task<string>.

+7

, , Task:

public async Task SaveToDb()

Task<T>, string:

public async Task<string> SaveToDb()
+1

All Articles