大家好,又见面了,我是你们的朋友全栈君。
大多时候,我们的循环结构的每一次迭代 依赖于上一次迭代的计算或行为。
但是,有的时候又不是这样。如果迭代之间彼此独立,并且程序运行在多核处理器的机器上,如果能将不同的迭代放在不同的处理器上并行处理的话,将会受益匪浅。Parallel.For 和 Parallel.ForEach结构就是这样做的。
一、Parallel.For
1、Parallel.For方法有12个重载:
public static ParallelLoopResult For(int fromInclusive, int toExclusive, Action<int> body);
public static ParallelLoopResult For(long fromInclusive, long toExclusive, Action<long> body);
public static ParallelLoopResult For(int fromInclusive, int toExclusive, Action<int, ParallelLoopState> body);
public static ParallelLoopResult For(long fromInclusive, long toExclusive, Action<long, ParallelLoopState> body);
public static ParallelLoopResult For(int fromInclusive, int toExclusive, ParallelOptions parallelOptions, Action<int> body);
public static ParallelLoopResult For(long fromInclusive, long toExclusive, ParallelOptions parallelOptions, Action<long> body);
public static ParallelLoopResult For(int fromInclusive, int toExclusive, ParallelOptions parallelOptions, Action<int, ParallelLoopState> body);
public static ParallelLoopResult For(long fromInclusive, long toExclusive, ParallelOptions parallelOptions, Action<long, ParallelLoopState> body);
public static ParallelLoopResult For<TLocal>(int fromInclusive, int toExclusive, Func<TLocal> localInit, Func<int, ParallelLoopState, TLocal, TLocal> body, Action<TLocal> localFinally);
public static ParallelLoopResult For<TLocal>(long fromInclusive, long toExclusive, Func<TLocal> localInit, Func<long, ParallelLoopState, TLocal, TLocal> body, Action<TLocal> localFinally);
public static ParallelLoopResult For<TLocal>(long fromInclusive, long toExclusive, ParallelOptions parallelOptions, Func<TLocal> localInit, Func<long, ParallelLoopState, TLocal, TLocal> body, Action<TLocal> localFinally);
public static ParallelLoopResult For<TLocal>(int fromInclusive, int toExclusive, ParallelOptions parallelOptions, Func<TLocal> localInit, Func<int, ParallelLoopState, TLocal, TLocal> body, Action<TLocal> localFinally);
最简单的一个是:public static ParallelLoopResult For(int fromInclusive, int toExclusive, Action<int> body);
参数fromInclusive: 是迭代的第一个索引号整数;
参数toExclusive:是迭代的最后一个索引+1的整数;
参数body:是接受单个输入参数的委托,body的代码在每一次迭代中执行一次。
2、实例
using System; using System.Threading.Tasks; // Must use this namespace
//使用Parallel.For语句(并行循环语句)的前提条件:迭代之间彼此独立。 namespace ExampleParallelFor { class Program { static void Main() { //i是索引号,即为For语句中接受的单个参数 Parallel.For( 0, 15, i => Console.WriteLine( “The square of {0} is {1}”, i, i * i ) ); } } }
运行结果:
发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/161806.html原文链接:https://javaforall.cn
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有