理解异步和等待 [英] Understanding async and await

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

问题描述

我正在尝试学习 MVC5 的细节,但我遇到了一些让我感到困惑的事情.在带有个人身份验证的 MVC5 项目默认附带的 accountController 中,异步登录和注册方法中有这行代码

I am trying to learn the details of MVC5 and I came across something that baffles me. In the accountController that comes by default with an MVC5 project with Individual Auth there is this line of code in the async Login and Register methods

var result = await UserManager.CreateAsync(user, model.Password);

我在这里阅读 http://msdn.microsoft.com/en-us/library/hh191443.aspx 这是一种正常做法,但我不明白为什么您会使用异步方法并在同一行中等待.在这里只使用接受相同参数的 .Create 方法不是更有意义吗?

I read here http://msdn.microsoft.com/en-us/library/hh191443.aspx that this is a normal practice, but I do not understand why you would ever use an asynchronous method and await in the same line. Wouldn't it make more sense to just use the .Create method that takes the same parameters here?

推荐答案

SomeMethod()await SomeMethodAsync() 的区别在于后者不会阻塞方法执行 IO 时的线程.因此,应用程序变得更具可扩展性,因为它可以使用较少数量的线程来处理相同数量的请求.

The difference between SomeMethod() and await SomeMethodAsync() is that the latter won't block a thread while the method performs IO. Because of that, the application becomes more scalable, because it can use smaller number of threads to serve the same number of requests.

如果您不关心可扩展性,那么选择这两个选项中的哪一个并不重要.但使用异步版本可能仍然更好,以确保您的应用程序面向未来,以便您的应用程序在可扩展性成为问题时表现良好.

If you don't care about scalability, then it doesn't matter much which of the two options are you going to choose. But it's probably still better to use the async version, to future-proof your application, so that your application behaves well when scalability becomes an issue.

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

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