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?