I am trying to understand the execution of Task.run inside Linq Select, In the below code when does the tasks gets executed.
IEnumerable<Task<ValidationResult>> processWorkSheetTasks = workBook
.Worksheets
.Select(worksheet => Task.Run(() => SomeCPUBoundWork(worksheet)));
try
{
var results = await Task.WhenAll(processWorkSheetTasks);
}
catch (Exception)
{
IEnumerable<AggregateException> exceptions = processWorkSheetTasks
.Where(executedTask => executedTask.Exception != null)
.Select(executedTask => executedTask.Exception);
throw new AggregateException(exceptions);
}
Doesn't the Task.Run
immediately queues the SomeCPUBoundWork
to run on the thread pool and return the Task<TResult>
handle for that work.
Does this mean, SomeCPUBoundWork
executes in parallel with the Select
statement that's getting executed by the main thread?
But When I debug, I see the breakpoint inside SomeCPUBoundWork
gets hit only after the line
List<ValidationResult> results = await Task.WhenAll(processWorkSheetTasks)
gets executed.
So, I am bit confused. Could someone please help me understand how the Task.Run
inside a linq works?