4

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

Patrick Hofman
  • 153,850
  • 22
  • 249
  • 325
user2915962
  • 2,691
  • 8
  • 33
  • 60
  • https://msdn.microsoft.com/en-us/library/hh191443.aspx http://www.dotnetperls.com/async http://stackoverflow.com/questions/14455293/async-and-await bunch of example you can look into. – Vinod Mar 30 '15 at 09:27
  • 1
    I doubt async/await for C# could be around as long as it has without examples of it in many places. As linked by @Vinod, a simple search would have found you these examples and many more. – Lukazoid Mar 30 '15 at 09:31
  • 1
    You'll want to also await `CreateTableAsync` before awaiting `InsertAsync`. – Jon Hanna Mar 30 '15 at 09:47

2 Answers2

7

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.

Lloyd
  • 29,197
  • 4
  • 84
  • 98
  • 1
    Erm...You should really just do `return DoSomethingAsync();` and drop the `async` from the sig. – Aron Mar 30 '15 at 09:56
  • @Aron Not if he's awaiting within the method IIRC? – Lloyd Mar 30 '15 at 10:06
  • No. `DoSomethingAsync()` already returns a `Task`. So you don't need the compiler to unwrap the `Task` `await` it, then wrap the result in another `Task`. – Aron Mar 30 '15 at 10:07
1

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()
Patrick Hofman
  • 153,850
  • 22
  • 249
  • 325