I've got some code which uses AsParallel().ForAll(...) which I was led to believe would block while all of the executions completed. This works perfectly with non async code.
For example the below code:
static void Main(string[] args)
{
var arr = new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 };
void printNumber(int numb)
{
Thread.Sleep(1000);
Console.WriteLine("Number: " + numb);
}
arr.AsParallel().ForAll(p =>
{
printNumber(p);
});
Console.WriteLine("Done!");
Console.ReadLine();
}
Results in an output of:
However, as soon as you make the same code async:
static void Main(string[] args)
{
var arr = new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 };
async Task printNumber(int numb)
{
await Task.Delay(1000);
Console.WriteLine("Number: " + numb);
}
arr.AsParallel().ForAll(async p =>
{
await printNumber(p);
});
Console.WriteLine("Done!");
Console.ReadLine();
}
The ForAll line does not block, and you can see that in the output:
Am I doing something wrong here? Is this expected behaviour?


await Task.WhenAll(arr.Select(p => printNumber(p)));