await in Parallel.foreach

user1438980 picture user1438980 · Apr 12, 2013 · Viewed 16.1k times · Source

I have an async method which will be used in Parallel.Foreach. in the async method there is await for a Task. However, in the test, seems there are no await behavior, the await Task didn't complete. What's the problem? Below is the code.

public void method1()
{
  Ilist<string> testList = new IList<string>(){"1","2","3"};
  Parallel.ForEach(testList, ()=>
  {
       method2();
  });
}
public async void method2()
{
   await Task.run(()=>{  some other codes here });  
}

Answer

Todd Menier picture Todd Menier · Jan 6, 2014

Late to answer, but it looks like you're trying to perform CPU-bound work in parallel, as opposed to performing I/O-bound work asynchronously. Parallel.ForEach is taking care of your parallelism, so no need for Task.Run, and async/await are gaining you nothing here. I'd suggest removing those bits from method2, so the whole thing simplifies to:

public void method1()
{
    Ilist<string> testList = new IList<string>(){"1","2","3"};
    Parallel.ForEach(testList, ()=>
    {
        method2();
    });
}
public void method2()
{
    // some other (plain old synchronous) code here
}