我想完成以下工作:
void Method()
{
Parallel.For(0, 100, i =>
{
// Do first set of actions
// Wait for all tasks to finish performing first set of actions
// Do second set of actions
});
}
我不能简单地做
void Method()
{
Parallel.For(0, 100, i =>
{
// Do first set of actions
});
Parallel.For(0, 100, i =>
{
// Do second set of actions
});
}
因为每个任务都会在第一组操作中实例化一个新对象,而第二组操作必须能够引用该实例。
我该怎么做?
最佳答案
我建议您按照第二个代码段的方式进行操作,但是要为这些新创建的对象保留一个数组-在循环中填充它们,然后在第二个中访问它们。
void Method()
{
var intermediates = new Intermediate[100];
Parallel.For(0, 100, i =>
{
// ...
intermediates[i] = ...;
});
Parallel.For(0, 100, i =>
{
var intermediate = intermediates[i];
// ... use intermediate
});
}
关于c# - 如何同步.NET中的并行 Action ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19552448/