0

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:

Output showing numbers before 'Done'

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:

Image showing 'Done' before the numbers

Am I doing something wrong here? Is this expected behaviour?

1
  • Another option (if you have few tasks) is await Task.WhenAll(arr.Select(p => printNumber(p))); Commented May 22 at 9:23

1 Answer 1

2

That's a bug in the code. This code essentially generates async void lambdas that can't be awaited. AsParallel() and Parallel.ForEach are used for data parallelism, not asynchronous execution.

Use Parallel.ForEachAsync instead:

await Parallel.ForEachAsync(arr,(p,cancellation)=>
{
        await printNumber(p);
});

Data parallelism means processing a large amount of in-memory data by using all available cores. Both AsParallel() and Parallel.For/ForEach partition the data into chunks to reduce the need of expensive synchronization and use roughly one worker task per core to process the chunks. AsParallel() is more specialized, using parallelized versions of LINQ operators like Where, OrderBy, Group, Select etc.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.