Async Methods Confusion [duplicate]

2019-05-17 01:45发布

This question already has an answer here:

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();
}

2条回答
家丑人穷心不美
2楼-- · 2019-05-17 02:26

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.

查看更多
冷血范
3楼-- · 2019-05-17 02:34

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.

查看更多
登录 后发表回答