C#WebAPI:等待任务.运行vs更多粒度等待 [英] c# webapi: Await Task.Run vs more granualar await

查看:442
本文介绍了C#WebAPI:等待任务.运行vs更多粒度等待的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据本文,我在WebApi控制器中使用async/await: https://msdn.microsoft.com/en-us/magazine/dn802603.aspx

I'm using async/await in WebApi Controllers according to this article: https://msdn.microsoft.com/en-us/magazine/dn802603.aspx

Hava在我的控制器中查看以下简化代码:

Hava look at this simplified code in my controller:

DataBaseData = await Task.Run( () => GetDataFunction()  );

GetDataFunction是将打开数据库连接,打开读取器并从数据库读取数据的函数.

GetDataFunction is a function that will open a database connection, open a reader and read the data from the database.

在许多示例中,我看到它的处理方式有所不同. GetDataFunction本身正在等待.在功能内,每个步骤都在等待. 例如:

In many examples I see it handled differently. The GetDataFunction itself is awaited. And within the function every single step is awaited. For example:

  • connection.OpenAsync
  • reader.ReadAsycnc
  • reader.IsDBNullAsync

为什么这是一种好习惯?为什么不只是为整个数据库访问启动一个线程(使用Task.Run)?

Why is this good practice? Why not just start a thread for the whole database access (with Task.Run)?

更新: 谢谢您的帮助.现在我明白了.我没有得到,异步Api不会自己启动线程.这确实有帮助: blog.stephencleary.com/2013/11/there -is-no-thread.html

Update: Thanks for the help. Now I got it. I did not get, that the asynchronous Api's do not start threads themselves. This really helped: blog.stephencleary.com/2013/11/there-is-no-thread.html

推荐答案

您链接的文章指出:

您可以通过等待Task.Run开始一些后台工作,但这样做没有任何意义.实际上,这会干扰ASP.NET线程池启发式方法,实际上会损害您的可伸缩性.通常,不要将工作排队到ASP.NET上的线程池中.

You can kick off some background work by awaiting Task.Run, but there’s no point in doing so. In fact, that will actually hurt your scalability by interfering with the ASP.NET thread pool heuristics... As a general rule, don’t queue work to the thread pool on ASP.NET.

换句话说,避免在ASP.NET上使用Task.Run.

In other words, avoid Task.Run on ASP.NET.

为什么这是一种好习惯?为什么不只是为整个数据库访问启动一个线程(使用Task.Run)?

Why is this good practice? Why not just start a thread for the whole database access (with Task.Run)?

这是因为异步API 不使用其他线程. async/await的全部要点是释放当前线程. 使用另一个线程.我有一篇博客文章描述了 async的工作原理而无需线程.

It's because the asynchronous APIs do not use other threads. The entire point of async/await is to free up the current thread; not use another thread. I have a blog post describing how async works without needing threads.

因此,Task.Run(或自定义线程)方法将在从数据库中获取数据时耗尽(阻塞)线程.正确的异步方法(例如EF6或ADO.NET异步API)不能;它们允许该请求线程在其他请求等待数据库响应时用于其他请求.

So, the Task.Run (or custom thread) approach will use up (block) a thread while getting data from the database. Proper asynchronous methods (e.g., EF6 or the ADO.NET asynchronous APIs) do not; they allow the request thread to be used for other requests while that request is waiting for the database response.

这篇关于C#WebAPI:等待任务.运行vs更多粒度等待的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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