Is it OK to do some async/await inside some .NET Parallel.ForEach() code?

后端 未结 4 587
轻奢々
轻奢々 2020-12-30 10:14

Given the following code, is it OK to do async/await inside a Parallel.ForEach ?

eg.

Parallel.ForEach(names, name          


        
4条回答
  •  一向
    一向 (楼主)
    2020-12-30 11:01

    No, It doesn't make sense to combine async with Paralell.Foreach.

    Consider the following example:

    private void DoSomething()
    {
        var names = Enumerable.Range(0,10).Select(x=> "Somename" + x);
        Parallel.ForEach(names, async(name) =>
        {   
            await Task.Delay(1000);
            Console.WriteLine("Name {0} completed",name);
        });
        Console.WriteLine("Parallel ForEach completed");
    }
    

    What output you will expect?

    Name Somename3 completed
    Name Somename8 completed
    Name Somename4 completed
    ...
    Parallel ForEach completed
    

    That's not what will happen. It will output :

    Parallel ForEach completed
    Name Somename3 completed
    Name Somename8 completed
    Name Somename4 completed
    ...
    

    Why? Because when ForEach hits first await the method actually returns, Parallel.ForEach doesn't know it is asynchronous and it ran to completion!. Code after await runs as continuation on another thread not "Paralell processing thread"

    Stephen toub addressed this here

提交回复
热议问题