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
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.
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With