Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 975
user2915962 Avatar asked Feb 10 '23 13:02

user2915962


2 Answers

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.

like image 98
Lloyd Avatar answered Feb 13 '23 01:02

Lloyd


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()
like image 24
Patrick Hofman Avatar answered Feb 13 '23 01:02

Patrick Hofman