user2915962
user2915962

Reputation: 2711

Async/await simple example

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

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

Now lets say that I want to save a User to my UserTable and when the saving is done I wish to retrieve 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 that I need a task somewhere, but im not completely sure how to do this. Thank you

Upvotes: 4

Views: 4872

Answers (2)

Lloyd
Lloyd

Reputation: 29668

You're mostly there already.

When returning void:

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

When returning a result:

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

The thing to note when returning a value in an async method is that you return the inner type (i.e in this case string) rather than a Task<string> instance.

Upvotes: 7

Patrick Hofman
Patrick Hofman

Reputation: 156928

If your code doesn't return any value, the signature should be this, returning Task:

public async Task SaveToDb()

Else, you would need to specify the return type as the type argument in Task<T>, string in this sample:

public async Task<string> SaveToDb()

Upvotes: 1

Related Questions