C# Parellel.For 和 Parallel.ForEach

简介:任务并行库(Task Parellel Library)是BCL的一个类库,极大的简化了并行编程。

使用任务并行库执行循环
C#当中我们一般使用for和foreach执行循环,有时候我们呢的循环结构每一次的迭代需要依赖以前一次的计算或者行为。但是有时候则不需要。如果迭代之间彼此独立,并且程序运行在多核处理器上,如果能将不同的迭代放到不同的处理器上并行处理,则会获益匪浅。Parallel.For和Parallel.ForEach就是为此而生的。

①使用Parallel.For 声明如下:

 这里可以看到 toExclusive这个参数,它是不含的, 在使用的时候传入参数要注意下。

 举个例子:

static void Main(string[] args)
{
    Parallel.For(0, 5, i =>
       {
           //打印平方
           Console.WriteLine("The Square of {0} is {1}", i, i * i);
       }
    );
    Console.ReadKey();
}

执行结果:

The Square of 0 is 0
The Square of 2 is 4
The Square of 1 is 1
The Square of 4 is 16
The Square of 3 is 9

从执行结果上我们可以看到,它不是按顺序执行的。那么问题来了,怎么让结果保持有序?

我们可以通过一个数组来存储执行的结果,例如下面的例子:

static void Main(string[] args)
{
    const int maxValues = 5;
    int[] Squares = new int[maxValues];

    Parallel.For(0, maxValues , i =>Squares[i] = i*i );

    for (int i = 0; i < maxValues; i++) Console.WriteLine("Square of {0} is {1}", i, Squares[i]);

    Console.ReadKey();
}

我们首先定义了一个数组,然后由于数组的下标已经定下来了,所以每次执行都会存入具体的位置,然后遍历结果的数组,就得到了有顺序的结果。

使用Parallel.ForEach

最简单的实现,声明如下:

举例:

static void Main(string[] args)
{
    string[] squares = new string[]
        {"We", "hold", "these", "truths", "to", "be", "self-evident", "that", "all", "men", "are", "created", "equal"};

    Parallel.ForEach(squares,
        i => Console.WriteLine(string.Format("'{0}' has {1} letters", i, i.Length)));

    Console.ReadKey();
}

结果:

'We' has 2 letters
'hold' has 4 letters
'these' has 5 letters
'to' has 2 letters
'truths' has 6 letters
'self-evident' has 12 letters
'that' has 4 letters
'be' has 2 letters
'men' has 3 letters
'are' has 3 letters
'created' has 7 letters
'equal' has 5 letters
'all' has 3 letters

这里同样可以看到,不是按顺序遍历的。 

原文地址:https://www.cnblogs.com/dcz2015/p/11015163.html