始终在ASP.NET MVC控制器中使用异步 [英] Always using Async in an ASP.NET MVC Controller

查看:94
本文介绍了始终在ASP.NET MVC控制器中使用异步的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近继承了一个ASP.NET MVC项目.在该项目中,开发人员正在使用 async 无处不在.我正在尝试评估它是否是一个好主意.具体来说,我目前正在查看控制器代码.

I recently inherited an ASP.NET MVC project. In that project, the developer is using async everywhere. I'm trying to assess if its a good idea or not. Specifically, I'm reviewing the controller code at the moment.

在控制器中,开发人员编写如下内容:

In the controllers, the developer wrote the stuff like the following:

public async Task<ActionResult> Index()
{
  return View();
}

相对于传统版本,它有什么优势吗?

Is there any advantage to this instead of the traditional version:

public ActionResult Index()
{
  return View();
}

如果在控制器代码中使用了 await ,我可以理解使用 async .很多时候,虽然它没有被使用.这种方法有什么道理吗?

I could understand using async if await was used in the controller code. A lot of times, its not being used though. Is there any justification for this approach?

推荐答案

否.在任何地方使用Async都不是一个好主意.

No. That's not a good idea to use Async everywhere.

关于缺少的等待,当 Async 方法不包含 Await 运算符时,编译器会发出警告.没有等待的Async方法将同步运行,这会使语义不正确.

Regarding the missing await the compiler issues a warning when an Async method does not contain an Await operator. An Async method without an await will run synchronously, which makes the semantics incorrect.

对于您的特定示例,该操作简单且运行时间短,这就是为什么使用Async/Await不会带来任何好处,并且不应该使用它的原因,因此您可以使用:

For your specific example, the operation is simple and short running, and that's why using Async/Await does not bring any benefits, and it shouldn't be used, so you are perfectly fine using:

public ActionResult Index()
{
    return View();
}

异步/等待应用于执行某种IO的控制器方法(例如,网络请求,数据库访问等).如果控制器方法正在执行CPU限制的工作(例如数学计算),则除非您的测量证明我错了,否则使用Async/Await实际上会使性能变差.

Async/Await should be used for controller methods that perform some kind of IO (e.g. Network requests, Database access etc.). If a controller method is doing CPU bound work (e.g. math. calculations), then using Async/Await can actually make performance worse, unless your measurements prove me wrong.

适用旧规则:测量两次,切割一次.

这篇关于始终在ASP.NET MVC控制器中使用异步的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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