我对在ASP中使用异步操作有一些担忧。净MVC。什么时候它能提高应用程序的性能,什么时候不能?

在ASP中处处使用异步操作好吗?净MVC吗? 关于可等待方法:当我想查询数据库(通过EF/NHibernate/其他ORM)时,我应该使用async/await关键字吗? 在一个操作方法中,我可以使用await关键字异步查询数据库多少次?


当前回答

我的经验是,今天很多开发人员使用async/await作为控制器的默认设置。

我的建议是,只有在你知道它对你有帮助的时候才使用它。

原因是,正如Stephen Cleary和其他人已经提到的,它会引入性能问题,而不是解决问题,并且它只会在特定的场景中帮助您:

高流量控制器 可伸缩的后端

其他回答

async actions help best when the actions does some I\O operations to DB or some network bound calls where the thread that processes the request will be stalled before it gets answer from the DB or network bound call which you just invoked. It's best you use await with them and it will really improve the responsiveness of your application (because less ASP input\output threads will be stalled while waiting for the DB or any other operation like that). In all my applications whenever many calls to DB very necessary I've always wrapped them in awaiatable method and called that with await keyword.

在ASP中处处使用异步操作好吗?净MVC吗?

在任何可以使用异步方法的地方这样做都是很好的,特别是当你在工作进程级别有性能问题时,这发生在大量数据和计算操作中。否则,不需要,因为单元测试将需要强制转换。

关于可等待方法:我是否应该使用async/await关键字当我 想查询一个数据库(通过EF/NHibernate/其他ORM)?

是的,最好对任何DB操作使用异步,以尽可能避免工作进程级别的性能问题。 注意,EF已经为大多数操作创建了许多异步选项,例如:

.ToListAsync()
.FirstOrDefaultAsync()
.SaveChangesAsync()
.FindAsync()

我可以使用await关键字查询数据库多少次 异步在一个单一的动作方法?

前途无量

我的经验是,今天很多开发人员使用async/await作为控制器的默认设置。

我的建议是,只有在你知道它对你有帮助的时候才使用它。

原因是,正如Stephen Cleary和其他人已经提到的,它会引入性能问题,而不是解决问题,并且它只会在特定的场景中帮助您:

高流量控制器 可伸缩的后端

我的5美分:

当且仅当你做IO操作时使用async/await,比如DB或外部服务webservice。 总是选择异步调用而不是DB。 每次查询DB时。

附注:第一点有例外情况,但你需要很好地理解异步内部。

作为一个额外的优势,如果需要,你可以并行执行很少的IO调用:

Task task1 = FooAsync(); // launch it, but don't wait for result
Task task2 = BarAsync(); // launch bar; now both foo and bar are running
await Task.WhenAll(task1, task2); // this is better in regard to exception handling
// use task1.Result, task2.Result

As you know, MVC supports asynchronous controllers and you should take advantage of it. In case your Controller, performs a lengthy operation, (it might be a disk based I/o or a network call to another remote service), if the request is handled in synchronous manner, the IIS thread is busy the whole time. As a result, the thread is just waiting for the lengthy operation to complete. It can be better utilized by serving other requests while the operation requested in first is under progress. This will help in serving more concurrent requests. Your webservice will be highly scalable and will not easily run into C10k problem. It is a good idea to use async/await for db queries. and yes you can use them as many number of times as you deem fit.

看看这里的优秀建议。