Parallel.ForEach 方法

简介:

Parallel.ForEach 方法并行的执行ForEach,它的重载方法也很多。

http://msdn.microsoft.com/zh-cn/library/system.threading.tasks.parallel.foreach.aspx。

最简单的是下面这个

ForEach<TSource>(IEnumerable<TSource>, Action<TSource>)

一个枚举器参数和一个Action委托。

 

static void Main(string[] args)
        {
            Parallel.ForEach("Hello, world", (c) =>
            {
                Console.WriteLine(c.ToString());
            });
        }
 
 
Because the loop body in a parallel For or ForEach is a delegate, you can’t exit
the loop early with a break statement. Instead, you must call Break or Stop on a
ParallelLoopState object:
由于并行的For和Foreach方法的循环体是一个委托,所以不能通过break退出循环体,你只能使用ParallelLoopState 对象的Break或者Stop方法来退出一个并行循环
For和Foreach所有的所有重载函数都接受一个Action<TSource,ParallelLoopState>委托,这里可以在循环体里使用ParallelLoopState。
 

 ParallelLoopState.Break()方法,:在完成当前的这轮工作之后,不再执行后继的工作,但在当前这轮工作开始之前“已经在执行”的工作,则必须完成。
      ParallelLoopState.Stop方法时,不但不会再创建新的线程执行并行循环,而且当前“已经在执行”的工作也应该被中止
 

      Stop  Break 的方法的区别非常微妙,需要仔细体会,可以简单地用两句话来表达:

n  ParallelLoopState.Stop 方法中止“当前”及“以后”的工作任务,会导致 ParallelLoopState 对象的 IsStop 属性值等于 true 

n  ParallelLoopState.Break() 方法仅中止“以后”的工作任务,会导致 ParallelLoopState 对象的 LowestBreakIteration 属性值等于 true 


 















本文转自cnn23711151CTO博客,原文链接:http://blog.51cto.com/cnn237111/538910  ,如需转载请自行联系原作者

相关文章
|
1天前
The type List is not generic; it cannot be parameterized with arguments <TbItem>
The type List is not generic; it cannot be parameterized with arguments <TbItem>
6 0
|
9月前
|
SQL
Parameter ‘id‘ not found. Available parameters are [collection, list]
Parameter ‘id‘ not found. Available parameters are [collection, list]
123 0
|
8月前
关于数组中forEach() 、map()、filter()、reduce()、some()、every()的总结
关于数组中forEach() 、map()、filter()、reduce()、some()、every()的总结
29 0
ES6常用数组方法总结(max,contant,some,every,filter,reduce,forEach,map)
1.求最大值(Math.max) 2.数组添加到另外一个数组的尾部(...扩展符) 3.复制数组 3.1数组直接赋值 3.2 es5通过concat方法进行克隆,不会影响原来数组 3.3 es6通过扩展字符串来实现克隆 4.用Object.keys清空对象的属性值 5.forEach,遍历数组,无返回值,不改变原数组 6.map遍历数组,返回新数组,不改变原数组 7.filter,过滤掉数组不符合条件的值,返回新数组,不改变原数组 8.reduce 9 some() 10.every
144 0
ES6常用数组方法总结(max,contant,some,every,filter,reduce,forEach,map)
4.1、Array数组常用的方法(map、push、sort、filter、join、split)
4.1、Array数组常用的方法(map、push、sort、filter、join、split)
108 0
Array数组对象的forEach,map,filter,reduce
刚才某人问了我一个问题。map怎么遍历,我刷刷刷就是一顿写。遍历么,forEach么,妥妥的。
122 0
|
SQL Java 数据库
PreparedStatement 模糊匹配 结果却:Parameter index out of range (1 > number of parameters, which is 0)
PreparedStatement 模糊匹配 结果却:Parameter index out of range (1 > number of parameters, which is 0)
383 0

热门文章

最新文章