大家好,又见面了,我是你们的朋友全栈君。
大多时候,我们的循环结构的每一次迭代 依赖于上一次迭代的计算或行为。
但是,有的时候又不是这样。如果迭代之间彼此独立,并且程序运行在多核处理器的机器上,如果能将不同的迭代放在不同的处理器上并行处理的话,将会受益匪浅。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 ) );
}
}
}
运行结果:
发布者:全栈程序员-用户IM,转载请注明出处:https://javaforall.cn/161806.html原文链接:https://javaforall.cn
【正版授权,激活自己账号】: Jetbrains全家桶Ide使用,1年售后保障,每天仅需1毛
【官方授权 正版激活】: 官方授权 正版激活 支持Jetbrains家族下所有IDE 使用个人JB账号...