终结了Parallel.ForEach [英] Finalizer for Parallel.ForEach

查看:128
本文介绍了终结了Parallel.ForEach的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何添加运行一旦所有的相似之处已经完成终结?



  Parallel.ForEach(条目,新ParallelOptions { MaxDegreeOfParallelism = 15},异步(进入)=方式> 
//使用入门的东西
});



我已经试过这样的,但它不会编译:

  Parallel.ForEach(条目,新ParallelOptions {MaxDegreeOfParallelism = 15},异步(进入)=方式> 
//做一些与入门
},()=> {//希望这会工作})。


解决方案

  1. 您应的不可以声明为 Parallel.ForEach 行动异步。如果使用等待的行动里面,控制流程返回 Parallel.ForEach 及其实施认为该操作是的完成的。这将导致非常的不同的行为比您预期的


  2. 要调用 Parallel.ForEach 收益当循环完成。当所有的行动已经在枚举所有元素做它返回。所以,你想要做的当所有的相似之处完成后可以正确的调用来做到什么:

      Parallel.ForEach(项,新ParallelOptions {MaxDegreeOfParallelism = 15} 
    (进入)=>
    //使用入门
    )的东西。
    DoSomethingWhenAllParallelsHaveCompleted();



How do I add a finalizer that runs once all parallels have completed?

Parallel.ForEach(entries, new ParallelOptions { MaxDegreeOfParallelism = 15 }, async (entry) =>
    // Do something with the entry.
});

I have tried like this but it doesn't compile:

Parallel.ForEach(entries, new ParallelOptions { MaxDegreeOfParallelism = 15 }, async (entry) =>
    // Do something with the entry.
}, () => { // Was hoping this would work. });

解决方案

  1. You should not declare the action for the Parallel.ForEach as async. If you use an await inside that action, the control flow is returned to Parallel.ForEach and its implementation "thinks" that the action is finished. This will lead to a very different behaviour than you expect.

  2. The call to Parallel.ForEach returns when the loop is completed. It returns when all actions have been done for all the elements in the enumeration. So whatever you want to do "when all parallels have completed" can be done right after that call:

    Parallel.ForEach(entries, new ParallelOptions { MaxDegreeOfParallelism = 15 }, 
             (entry) =>
             // Do something with the entry.
    );
    DoSomethingWhenAllParallelsHaveCompleted();
    

这篇关于终结了Parallel.ForEach的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆