大多时候,我们的循环结构的每一次迭代 依赖于上一次迭代的计算或行为。
但是,有的时候又不是这样。如果迭代之间彼此独立,并且程序运行在多核处理器的机器上,如果能将不同的迭代放在不同的处理器上并行处理的话,将会受益匪浅。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://bianchenghao.cn/35380.html