Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Task.Run() in async method causes thread pool starvation?

I have this piece of code in my .netcore application

[HttpPost]
[Route("doSomething")]
public async Task<IActionResult> DoSomethingAsync([FromBody] Input input)
{
    // Do Something
    var task1 = Task.Run(async () => 
    {
        await taskFactory.DoTask(input);
    });

    // Do Something Differently
    var task2 = Task.Run(async () => 
    {
        await taskFactory.DoAnotherTask(input);
    });

    await Task.WhenAll(task1, task2);

    return Accepted();
}

DoTask() and DoAnotherTask() are both independent of each other and can be executed in parallel but they have to be awaited until both of them are in completed status.

So, I created two tasks and awaited them using Task.WhenAll().

But I have got a review comment to not use Task.Run() in an async method as it can lead to thread pool starvation.

Question 1: How does my code leading to thread pool starvation?
Question 2: If it is leading to thread pool starvation, how can I run both tasks in parallel?

like image 431
Code-47 Avatar asked Oct 15 '25 04:10

Code-47


1 Answers

To answer your question with confidence we must know the implementation of the DoTask and DoAnotherTask methods. Without knowing it we could just assume that they are implemented properly and follow the etiquette for async methods, which is to return a Task immediately, without blocking the calling thread. Under this assumption, the answer is: No, your code doesn't lead to thread pool starvation. This is because the ThreadPool thread employed by Task.Run has a negligible amount of work to do, which is just to create a Task object, so it will be returned back to the ThreadPool almost immediately.

It should be pointed out that although wrapping well behaved async delegates with Task.Run has negligible impact to the health of the ThreadPool, it offers no benefit either. Take a look at this semi-related question: Is Task.Run considered bad practice in an ASP .NET MVC Web Application?

like image 88
Theodor Zoulias Avatar answered Oct 17 '25 20:10

Theodor Zoulias



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!