在Parallel.foreach中等待

use*_*980 9 c# task-parallel-library async-await parallel.foreach

我有一个将在Parallel.Foreach中使用的异步方法.在异步方法中有等待任务.但是,在测试中,似乎没有等待行为,await Task没有完成.有什么问题?下面是代码.

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 });  
}
Run Code Online (Sandbox Code Playgroud)

Tod*_*ier 6

后来回答,但看起来你正试图并行执行CPU绑定工作,而不是异步执行I/O绑定工作.Parallel.ForEach正在照顾你的并行性,所以不需要Task.Run,​​并且async/ await这里没有任何东西.我建议从method2中删除这些位,所以整个过程简化为:

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
}
Run Code Online (Sandbox Code Playgroud)


Lee*_*Lee 3

void async方法是“即发即忘”,并且无法等待它们完成。当method2在并行循环中调用时,它会立即返回,因此您的循环仅确保在method2循环完成之前创建任务。

您可以更改返回类型,method2Task将允许您等待操作的结果,例如

public async Task method()
{
     await Task.Run(() { some other code here });
}
Run Code Online (Sandbox Code Playgroud)

你可以在循环中等待

method2().Wait();
Run Code Online (Sandbox Code Playgroud)

method2尽管这样做并不比直接在 foreach 委托中运行任务主体更好。