Parallel.For循环 和 Parallel.ForEach循环

大多时候,我们的循环结构的每一次迭代 依赖于上一次迭代的计算或行为。

但是,有的时候又不是这样。如果迭代之间彼此独立,并且程序运行在多核处理器的机器上,如果能将不同的迭代在不同的处理器上并行处理的话,将会受益匪浅。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 ) );
      }
   }
}

运行结果:

 

 

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值