且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

单核心计算机上的Web API和异步/等待收益

更新时间:2022-12-23 08:53:30

但是,我给人的印象是,将所有各种调整大小包装到一个方法中并异步运行,这至少会暂时将Web API线程返回到池中,以处理另一个请求(而常规线程运行调整大小的任务)),那是一件好事.

But I'm under the impression that wrapping all the various resizes into a method and running that asynchronously will at least return the Web API thread to the pool, temporarily, to process another request (while a regular thread runs the resizing tasks), and that that is a good thing.

不,不是这样.如果您有真正的异步工作要做,那么可以,通过使用 async await ,您将获得可伸缩性的好处.但是,您的工作受CPU限制,因此代码如下:

No, not really. If you had true asynchronous work to do, then yes, you'd get a scalability benefit from using async and await. However, your work is CPU-bound, so code like this:

var photoUris = await Task.Run(() => _photoService.ProcessImages(photoStream);

仅使用另一个线程池线程( Task.Run )结束,从而允许请求线程返回线程池.因此,这实际上是增加的开销,并没有给您带来任何可扩展性的好处.

just ends up using another thread pool thread (Task.Run), allowing the request thread to return to the thread pool. So it's actually adding overhead and doesn't give you any scalability benefit.

在ASP.NET上,如果您有CPU工作要做,只需直接调用该方法即可.不要将其包装在 Task.Run 中.

On ASP.NET, if you have CPU-bound work to do, just call that method directly. Don't wrap it in Task.Run.