1

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?

Dai
  • 141,631
  • 28
  • 261
  • 374
Vicky
  • 11
  • 6
  • Is `workbook.Worksheets` an Excel COM Automation object? If so, I don't think you should be doing this at all because Office's COM Automation objects are not thread-safe. – Dai Mar 07 '23 at 16:51
  • 3
    LINQ use lazy execution. see here https://stackoverflow.com/questions/49527642/understanding-lazy-evaluation-in-linq-in-c-sharp – Serg Mar 07 '23 at 16:52
  • No workbook.Worksheets is not Excel COM Automation object, I am using an open source library, but thanks for the heads up, I will make sure to check whether it is thread safe or not. – Vicky Mar 07 '23 at 17:04
  • 1
    Side effects and LINQ should not be mixed together. – InBetween Mar 07 '23 at 17:13
  • 1
    From the documentation: [Deferred execution and lazy evaluation](https://learn.microsoft.com/en-us/dotnet/standard/linq/deferred-execution-lazy-evaluation). – Theodor Zoulias Mar 07 '23 at 17:46

0 Answers0