简介:任务并行库(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

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

C# Parellel.For 和 Parallel.ForEach的更多相关文章

  1. Parallel.Foreach

    随着多核时代的到来,并行开发越来越展示出它的强大威力! 使用并行程序,充分的利用系统资源,提高程序的性能.在.net 4.0中,微软给我们提供了一个新的命名空间:System.Threading.Ta ...

  2. [译]何时使用 Parallel.ForEach,何时使用 PLINQ

    原作者: Pamela Vagata, Parallel Computing Platform Group, Microsoft Corporation 原文pdf:http://download.c ...

  3. Parallel.ForEach , ThreadPool.QueueUserWorkItem

    using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.T ...

  4. Parallel.ForEach() 并行循环

    现在的电脑几乎都是多核的,但在软件中并还没有跟上这个节奏,大多数软件还是采用传统的方式,并没有很好的发挥多核的优势. 微软的并行运算平台(Microsoft’s Parallel Computing ...

  5. Parallel for-each loops in .NET C# z

    An IEnumerable object An Action of T which is used to process each item in the list List<string&g ...

  6. Parallel.Foreach的并发问题解决方法-比如爬虫WebClient

    场景五:线程局部变量 Parallel.ForEach 提供了一个线程局部变量的重载,定义如下: public static ParallelLoopResult ForEach<TSource ...

  7. Parallel.Foreach的全部知识要点【转】

    简介 当需要为多核机器进行优化的时候,最好先检查下你的程序是否有处理能够分割开来进行并行处理.(例如,有一个巨大的数据集合,其中的元素需要一个一个进行彼此独立的耗时计算). .net framewor ...

  8. C# 使用Parallel并行开发Parallel.For、Parallel.Foreach实例

    using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.N ...

  9. Parallel.ForEach 多线程 声明失败 "未将对象引用设置到对象的实例"

    x using System; using System.Collections.Generic; namespace Parallel.ForEach { class Program { //代码结 ...

随机推荐

  1. 图像Resize中0.5像素中心对齐的问题

    目录 0.5像素对齐的问题 0.5像素对齐的问题 1. 问题提出 在进行图像缩放时,偶尔会看到一些比较奇怪的代码,其中有一个就是0.5像素中心对齐的问题,例如在OpenCV线性插值的代码中有类似如下操 ...

  2. 渡鸦币(Raven)钱包交叉编译详解

    1 环境准备 1.1 准备Ubuntu 准备虚拟机或物理机,操作系统为Ubuntu 16.04 1.2 安装Mingw sudo apt-get install g++-mingw-w64-i686 ...

  3. python中通过客户端IP拿到所在城市和当地天气信息—附带项目案例

    熟悉老一代QQ的小伙伴可能都知道,很早以前的QQ,鼠标滑到头像的位置,你的位置和IP会在详情页显示,那么这个是如何做到的呢?下面我们就来玩一玩这个东西 首先,需求分析: 1.拿到客户端IP 2.通过I ...

  4. U盘防病毒

    1.待查 http://jingyan.baidu.com/article/a3f121e4ced14ffc9052bbca.html

  5. CentOs7环境下手动配置JDK7

    下载: JDK7下载地址:http://www.oracle.com/technetwork/java/javase/downloads/java-archive-downloads-javase7- ...

  6. python学习-44 程序的解耦 (不是特别懂的,回头在复习)

    import os def file_handler(backend_data,res=None,type='fetch'): # 查询功能 if type == 'fetch': with open ...

  7. go实现简单的tcp编程

    服务端的代码 package main import ( "fmt" "net" ) func main () { fmt.Println("star ...

  8. golang以服务方式运行

    golang开发的二进制程序,一般需要长期后台运行的,在linux上可以用supervisor或upstart或systemd等第三方守护进程来实现.其实golang自己也可以实现以服务的形式常驻后台 ...

  9. Unity中的Character Controller

    Unity中默认提供了一个Character Controller的组件用于实现角色控制,一个3D的游戏物体,可以直接添加.Character Controller会自动模拟出Capsule Coll ...

  10. poj 1837 天平问题(01背包变种)

    题意:给你n个挂钩,m个砝码,要求砝码都用上,问有多少中方案数 题解:对于这道题目的状态,我们定义一个变量j为平衡度,当j=0的时候,表明天平平衡.定义dp[i][j]表达的含义为使用前n个砝码的时候 ...