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
这里同样可以看到,不是按顺序遍历的。
C# Parellel.For 和 Parallel.ForEach的更多相关文章
- Parallel.Foreach
随着多核时代的到来,并行开发越来越展示出它的强大威力! 使用并行程序,充分的利用系统资源,提高程序的性能.在.net 4.0中,微软给我们提供了一个新的命名空间:System.Threading.Ta ...
- [译]何时使用 Parallel.ForEach,何时使用 PLINQ
原作者: Pamela Vagata, Parallel Computing Platform Group, Microsoft Corporation 原文pdf:http://download.c ...
- Parallel.ForEach , ThreadPool.QueueUserWorkItem
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.T ...
- Parallel.ForEach() 并行循环
现在的电脑几乎都是多核的,但在软件中并还没有跟上这个节奏,大多数软件还是采用传统的方式,并没有很好的发挥多核的优势. 微软的并行运算平台(Microsoft’s Parallel Computing ...
- 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 ...
- Parallel.Foreach的并发问题解决方法-比如爬虫WebClient
场景五:线程局部变量 Parallel.ForEach 提供了一个线程局部变量的重载,定义如下: public static ParallelLoopResult ForEach<TSource ...
- Parallel.Foreach的全部知识要点【转】
简介 当需要为多核机器进行优化的时候,最好先检查下你的程序是否有处理能够分割开来进行并行处理.(例如,有一个巨大的数据集合,其中的元素需要一个一个进行彼此独立的耗时计算). .net framewor ...
- C# 使用Parallel并行开发Parallel.For、Parallel.Foreach实例
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.N ...
- Parallel.ForEach 多线程 声明失败 "未将对象引用设置到对象的实例"
x using System; using System.Collections.Generic; namespace Parallel.ForEach { class Program { //代码结 ...
随机推荐
- socket 异步接收连接和接收数据
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; usin ...
- Leetcode之148. Sort List Medium
https://leetcode.com/problems/sort-list/ Sort a linked list in O(n log n) time using constant space ...
- YIIMP矿池搭建
本文将以Verge(x17)和Raven(x16rv2)为例子来说明多算法矿池YIIMP的搭建过程. 1 环境准备 1.1 准备Ubuntu 准备虚拟机或物理机,操作系统为Ubuntu 18.04,之 ...
- 【数据库开发】在Windows上以服务方式运行 MSOPenTech/Redis
在Windows上以服务方式运行 MSOPenTech/Redis ServiceStack.Redis 使用教程里提到Redis最好还是部署到Linux下去,Windows只是用来做开发环境,现在这 ...
- FineReport工具
PostgreSQL链接问题: 正常安装FineReport工具和PostgreSQL数据库之后,在FineReport工具当中链接数据库显示连接失败的原因是因为FineReport安装包里面没有Po ...
- MapReduce 工作流程
1. Map 阶段 ============================================= 2. Reduce 阶段
- 在airflow的BashOperator中执行docker容器中的脚本容易忽略的问题
dag模板 from airflow import DAG from airflow.operators.bash_operator import BashOperator from airflow. ...
- ASP.NET请求过程-Handler
什么事Handler asp.net程序所有的请求都是handler处理的.以前的webform我们访问的地址是xxxxx.aspx地址,其实他也会到一个handler(我们写的业务代码都在handl ...
- python学习--12 基本数据类型
数字 int -int 功能 1.转换 例如: a = '123' # 字符串print(type(a),a)b = int(a) # 将字符串转换成intprint(type(b),b) 运算结果 ...
- recover函数捕获异常
package main import ( //"fmt" "time" ) func test () { var m map[string]int m[&qu ...