Marco Scabbiolo Marco Scabbiolo - 3 months ago 7
C# Question

Await for a list of tasks, one at a time

I have the following code, and I'm not sure if it's going to run the tasks one at the time, or run all of them at the same time, and await for all of them to finish.

Dictionary<TemporaryAdditionalData, Exception> rejected = new Dictionary<TemporaryAdditionalData, Exception>();

await Task.WhenAll(additionalData
.SelectMaybe(async adda =>
await this.InsertTemporallyAdditionalData(
guid, adda.Order, adda.ID, adda.Value, adda.IsMandatory
),
out rejected
).ToArray()
);

return rejected;


I think the
SelectMaybe
method is not relevant here, it's just an extension to LINQ's
Select
that automatically catches exceptions and returns them.

1) The tasks will run one by one or all at the same time?

2) Whatever is the answer to 1, how could I write the same code to do the opposite?

Answer

Tasks will be executed in parallel. If you would like them to execute sequentially, you can write a simple loop like this:

foreach (var adda in additionalData) 
{        
    try 
    {
       await this.InsertTemporallyAdditionalData(
           guid, adda.Order, adda.ID, adda.Value, adda.IsMandatory
       );
    }
    catch (Exception ex) 
    {
         rejected[adda] = ex;
    }
}
Comments