This question already has an answer here:
- async/await function comparison 3 answers
I'm trying to wrap my head around asynchronous methods and I am wondering what the difference is between the following two methods.
public Task Add(Tenant tenant)
{
DbContext.Tenants.Add(tenant);
return DbContext.SaveChangesAsync();
}
public async Task Add(Tenant tenant)
{
DbContext.Tenants.Add(tenant);
await DbContext.SaveChangesAsync();
}
First one is synchronous method, which returns
Task
.Second one is asynchronous method, which awaits another asynchronous operation at the end of the method (tail-call).
There is a proposed optimization for Roslyn, which will convert second one to first one, when possible.
Your second variant introduces a slight overhead. The compiler has to emit a lot of boilerplate to effectively allow the current method to be resumed.
In both cases, what your method returns is a
Task
which will be completed onceSaveChangesAsync
has completed all of the requested work asynchronously. But in the first case, what you're returning is the exactTask
thatSaveChangesAsync
returned itself.Whereas in the second case, what you're returning is a new
Task
object. And then, as I say, the overhead to allow your method to mark this newTask
as complete as soon asSaveChangesAsync
marks itsTask
as complete.