在Parallel.foreach中等待
本文关键字:等待 foreach Parallel | 更新日期: 2023-09-27 18:08:53
我有一个异步方法,将在Parallel.Foreach中使用。在async方法中有等待任务。然而,在测试中,似乎没有等待行为,等待任务没有完成。有什么问题吗?代码如下:
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 });
}
回答晚了,但看起来您正在尝试并行执行cpu绑定的工作,而不是异步执行I/o绑定的工作。Parallel.ForEach
负责处理并行性,所以不需要Task。跑,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
}
void async
方法是"先发后忘",没有办法等待它们完成。当在并行循环中调用method2
时,它会立即返回,因此循环只是确保在循环完成之前创建了method2
中的任务。
您可以将method2
的返回类型更改为Task
,这将允许您等待操作的结果,例如
public async Task method()
{
await Task.Run(() { some other code here });
}
可以用
在循环中等待method2().Wait();
尽管这样做并不比直接在foreach委托中运行method2
中的任务体好。