有没有相当于“继续”的词?在 Parallel.ForEach 中?
我正在将一些代码移植到 Parallel.ForEach
并在代码中出现 continue
错误。我可以在 Parallel.ForEach 中使用与 foreach 循环中的 continue 功能等效的东西吗?
Parallel.ForEach(items, parallelOptions, item =>
{
if (!isTrue)
continue;
});
I am porting some code to Parallel.ForEach
and got an error with a continue
I have in the code. Is there something equivalent I can use in a Parallel.ForEach
functionally equivalent to continue
in a foreach
loop?
Parallel.ForEach(items, parallelOptions, item =>
{
if (!isTrue)
continue;
});
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
(主体只是为每个项目调用的函数)
(the body is just a function called for each item)
当您将循环转换为 Parallel.Foreach 逻辑的兼容定义时,您最终使语句主体成为 lambda。嗯,这是一个由 Parallel 函数调用的操作。
因此,请将
continue
替换为return
,并使用Stop()
或Break()
语句来中断。When you converted your loop into a compatible definition for the Parallel.Foreach logic, you ended up making the statement body a lambda. Well, that is an action that gets called by the Parallel function.
So, replace
continue
withreturn
, and break withStop()
orBreak()
statements.只需重构您的代码,就没有理由在高级语言中使用 continue 。
您的示例将表明以下内容:
危险是当您的 continue 上面的代码变得更大并且您在 6 个月后回来进行一些更改时会错过继续。 (我也总是在任何 if 输出周围放入大括号,以防止在 if 内添加内容)。
我会怎么做。
因此,上面的代码不会使用或节省更多的系统资源,但这确实意味着,如果您快速扫描代码,您将立即看到仅对某些元素执行的代码显然位于条件语句内,因为它本质上是选项卡式的。
如果你没有在 continue 上面放置任何代码,那么将其放在那里是毫无意义的(并且浪费 cpu 周期和 RAM),在这种情况下,我会重构为如下所示:
现在,在上述情况下,你可以不想使用静态,现代 C# 应该能够从不同的线程调用静态扩展到主线程,这只是意味着不是在每个对象上存储函数的新副本,而是存储它一次,该进程会缓存在程序打开的每个线程中。
相反,您可以查看对象上的 Bool,或者如果您想绝对确定是否已完成是否在处理中包含此项的检查,那么倒数第二个示例正是您将使用的。
Simply refactor your code, there is little reason to use a continue in high level languages.
Your example would indicate something like:
The danger is when the
code above your continue
gets larger and you miss the continue when you come back in 6 months to make some changes. (I also always put in braces around any if output to protect against additions inside the if).How I would do it.
So the code above doesn't use or save any more system resources but it does mean if you are quickly scanning the code you will immediately see that the code only done to some elements is obviously inside a conditional due to the tabbed in nature of it.
If you are not putting any code above the continue then it is pointless (and a waste of cpu cycles & RAM) to have it in there, in that case I would refactor to something like the following:
Now in the above case you may not want to use a static, modern C# should be able to call a static extension from a different thread to main, it just means instead of storing a new copy of the function on every object, you store it once and the process is cached in every thread that is opened by your program.
Instead you could be looking at a Bool on the object, or if you want to make absolutely sure the check on whether to include this item in the processing is done or not, then the second last example is exactly what you would use.