Can you increase throughput using Task.Run on synchronous code in the controller?

In my controller, I need to call the BlockingHttpRequest() method, which makes an HTTP request. It is relatively slow, and blocks the flow.
I cannot reorganize this method to make it asynchronous.

Is it better to wrap this method in Task.Run to at least free the UI / controller thread?
I'm not sure if it really improves anything or just does more work.

 public class MyController : Controller { public async Task<PartialViewResult> Sync() { BlockingHttpRequest(); return PartialView(); } public async Task<PartialViewResult> Async() { await Task.Run(() => BlockingHttpRequest()); return PartialView(); } } 

In practice, I have a couple of similar situations where BlockingHttpRequest() takes 500 ms and 5000 ms, respectively.


I understand that Task.Run() will not return my function before.

I thought there might be some benefit to increasing bandwidth. Having freed up the controller thread, does it make it accessible to other users? This would mean that in MVC there is a difference between controller threads and workflow threads.

+5
source share
2 answers

Having freed up the controller thread, does it make it accessible to other users?

Yes it is.

This would mean that in MVC there is a difference between controller threads and workflow threads.

No no. Since, just as you free up a thread thread thread that can now execute other requests, you also consume a thread thread thread thread that can no longer handle other requests. Thus, the total number of threads that can work with other requests is the same.

I thought there might be some benefit to increasing bandwidth.

No. You spend time switching between threads, waiting for a new worker to be scheduled, and other overheads are associated with the work you do and you get nothing in return.

+3
source

Since the method blocks, moving it to another thread gives nothing. It simply destroys one thread instead of the other, both of which were created equal.

In addition, since the stream is still wasted, there is no increase in scalability or bandwidth.

0
source

Source: https://habr.com/ru/post/1260128/


All Articles