Async Methods Confusion [duplicate]

亡梦爱人 提交于 2019-12-22 11:02:50

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!