Return (or not) id in the async method

c# entity-framework-core npgsql postgresql

Question

Given the following classes:

class Account
{
     [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
     public long Id {get; set;}
     ...
}

class AccountModel
{
    public long Id {get; set;}
    ...
}

If I called this method:

async Task AddAccountAsync(AccountModel model)
{
    Account entity = CreateFromModel(model);
    DbContext.Add(entity);
    await DbContext.SaveChangesAsync();
    model.Id = entity.Id;
}

model.Id after running (with await) is -9223372036854775808.

But if I use this instead:

async Task<long> AddAccountAsync(AccountModel model)
{
    Account entity = CreateFromModel(model);
    DbContext.Add(entity);
    await DbContext.SaveChangesAsync();
    return entity.Id;
}

it returns the right value. Why so?

1
1
7/31/2018 9:42:30 PM

Popular Answer

This code returns a Task

async Task AddAccountAsync(AccountModel model)

So, you would need to Wait for the Task to finish. Typically like this:

var result = AddAccountAsync(model);
result.Wait()

Mixing Wait and await is bit dangerous ! You could typically end up with deadlocks. The better option would be to use await on the Task

await result

After the call finishes, I would expect your model object to have the correct value.

The above technique is useful in scenarios where you are calling multiple async methods and finally have to wait for all of them to finish.

eg.

var result1Task = Method1Async();
var result2Task = Method2Async();
var result3Task = Method3Async();

...
--finally
await Task.WhenAll(result1Task, result2Task, result3Task);

Your second method returns an actual value itself

async Task<long> AddAccountAsync(AccountModel model)

you would typically await the above method call and get back the result

var id = await AddAccountAsync(model)

You would have seen that the comments in your question is asking about: how exactly you are calling these methods ?

The way you call these methods will give a clue to why the values are not as per your expectation.

You can explore Stephen Cleary's blog about async/await: http://blog.stephencleary.com/2012/02/async-and-await.html

The Async Composition section would be relevant to your query.

0
8/11/2018 9:46:44 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow