Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

In my controller I need to call a method BlockingHttpRequest() which makes an http request. It is relatively slow running, and blocks the thread.
I am not in a position to refactor that method to make it async.

Is it better to wrap this method in a Task.Run to at least free up a UI/controller thread?
I'm not sure if this really improves anything, or just makes 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 situations like this, where BlockingHttpRequest() takes 500ms and 5000ms respectively.


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

I thought that there might be some benefit of increased throughput. By freeing up the controller's thread, does that make it available to other users? This would imply that in MVC there is a difference between controller threads and background worker threads.

like image 663
Buh Buh Avatar asked Oct 17 '22 22:10

Buh Buh


1 Answers

By freeing up the controller's thread, does that make it available to other users?

Yes, it does.

This would imply that in MVC there is a difference between controller threads and background worker threads.

No, there is not. Because just as you're freeing up a thread pool thread that can now go service other requests, you're also consuming a new thread pool thread that now cannot go service other requests. So the total number of threads able to go work on other requests is the same.

I thought that there might be some benefit of increased throughput.

There is not. You're wasting some time context switching between threads, waiting for the new worker to be scheduled, and other overhead related to the work that you're doing, and you're getting nothing in return.

like image 176
Servy Avatar answered Nov 12 '22 23:11

Servy