简介:任务并行库(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. SQL Server数据同步交换

    一.为了解决数据同步汇聚,数据分发,数据转换,数据维护等需求,TreeSoft将复杂的网状的同步链路变成了星型数据链路.     TreeSoft作为中间传输载体负责连接各种数据源,为各种异构数据库之 ...

  2. w10环境下Hexo博客搭建

    w10使用hexo+github手把手搭建自己的第一个博客 对一个程序员来说,博客的重要性不言而喻,不但可以积累知识,还可以更好的给别人分享自己的心得.今天就以时下比较流行的hexo博客搭建属于自己的 ...

  3. (二)MVC项目+c3p0连接池

    一.项目架构 注:删除了原有的数据库工具,添加了c3p0数据库工具类,添加了c3p0的配置文件,修改了Dao类以及servlet类 二.修改或添加的类 1.C3p0Helper(暂时不了解事务回滚之类 ...

  4. 【计算机视觉】BING: Binarized Normed Gradients for Objectness Estimation at 300fps

    BING: Binarized Normed Gradients for Objectness Estimation at 300fps Ming-Ming Cheng, Ziming Zhang, ...

  5. table列表全选

    <table><tr><td><input type="checkbox" /></td><td></ ...

  6. netcore mvc菜单,角色,权限

    netcore mvc快速开发系统(菜单,角色,权限[精确到按钮])开源 AntMgr https://github.com/yuzd/AntMgr 基于netcore2.0 mvc 开发的 快速搭建 ...

  7. python邮件发送自动化测试报告

    话不多说直接贴代码 # encoding: utf-8import smtplib #发送邮件模块from email.mime.text import MIMEText #邮件内容from emai ...

  8. vector iterators incompatible

    字面翻译迭代器类型不兼容 今天同事遇到的这个问题算是一个习惯性写法的问题.描述一下代码: struct Track{}; class BaseTrack { - std::vector<Trac ...

  9. laravel6.0路由

    1.基本路由路由定义在routes目录下,路由执行是在控制器之前,路由路径 routes目录下api.php 关于接口路由定义文件包含的路由位于 api 中间件组约束之内,支持频率限制功能,这些路由是 ...

  10. python学习-11 运算符2

    布尔值 1.真 true 假false name = 'abc' c = 'c' in name print(c) 运算结果: True Process finished with exit code ...