问题
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();
}
回答1:
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.
回答2:
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 once SaveChangesAsync
has completed all of the requested work asynchronously. But in the first case, what you're returning is the exact Task
that SaveChangesAsync
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 new Task
as complete as soon as SaveChangesAsync
marks its Task
as complete.
来源:https://stackoverflow.com/questions/35941724/async-methods-confusion