异步方法混乱 [英] Async Methods Confusion

查看:104
本文介绍了异步方法混乱的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图环绕异步方法我的头,我想知道有什么区别以下两种方法之间。

 公共任务添加(租客租客)
{
    DbContext.Tenants.Add(租客);
    返回DbContext.SaveChangesAsync();
}公共异步任务添加(租客租客)
{
    DbContext.Tenants.Add(租客);
    等待DbContext.SaveChangesAsync();
}


解决方案

第一个是同步的方法,它返回工作。结果
第二个是的异步的方法,在方法(尾调用)结束等待下一个异步操作。

有一个提出的优化了解罗斯林,将第二个转换成第一在可能的情况。

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.

这篇关于异步方法混乱的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆