异步/的await功能对比 [英] async/await function comparison

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

问题描述

我想了解异步/等待,如果这两种方法的工作identically.If不是你能解释我想知道为什么吗?

 公共异步任务<客户> GetClient()
        {
            返回等待_clientRepository.GetAll(),其中(X => x.Id == 1)。.FirstOrDefaultAsync();
        }        公共任务<客户> GetClient2()
        {
            返回Task.FromResult(_clientRepository.GetAll()其中(x =方式> x.Id == 1).FirstOrDefault());
        }公共异步任务的run()
{
        VAR的结果=等待GetClient();
        VAR结果2 =等待GetClient2();
}


解决方案

他们是不一样的,当你添加async关键字启用以下两个功能。


  • 被标记的异步方法可以使用​​等待或等待指定悬挂点。该运营商的await告诉异步方法不能继续过去的这一点,直到等待的异步过程完成编译。在此同时,控制返回到异步方法的调用者。

    异步方法在一个前的await pression悬挂不构成从方法的退出,finally块不会运行。


  • 被标记的异步方法本身可以通过调用它的方法来等待。


您应该在这里读异步/的await文档: https://开头MSDN。 microsoft.com/en-us/library/hh191443.aspx

I am trying to understand async/await and I am wondering if both methods work identically.If not can you explain why?

       public async Task<Client> GetClient()
        {
            return await _clientRepository.GetAll().Where(x => x.Id == 1).FirstOrDefaultAsync();
        }

        public Task<Client> GetClient2()
        {
            return Task.FromResult(_clientRepository.GetAll().Where(x => x.Id == 1).FirstOrDefault());
        }

public async Task Run()
{
        var result = await GetClient();
        var result2 = await GetClient2();
}

解决方案

They are not the same, when you add the async keyword you enable the following two capabilities.

  • The marked async method can use Await or await to designate suspension points. The await operator tells the compiler that the async method can't continue past that point until the awaited asynchronous process is complete. In the meantime, control returns to the caller of the async method.

    The suspension of an async method at an await expression doesn't constitute an exit from the method, and finally blocks don’t run.

  • The marked async method can itself be awaited by methods that call it.

You should read the async/await documentation here: https://msdn.microsoft.com/en-us/library/hh191443.aspx

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

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