網站首頁 編程語言 正文
簡介:任務并行庫(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
相關推薦
- 2022-03-30 py3nvml實現GPU相關信息讀取的案例分析_python
- 2022-04-25 ASP.NET?Core?MVC中過濾器工作原理介紹_實用技巧
- 2022-09-29 解決react組件渲染兩次的問題_React
- 2022-04-20 Python設計模式中的行為型策略模式_python
- 2023-02-03 python本地降級pip的方法步驟_python
- 2022-11-30 Python利用yarl實現輕松操作url_python
- 2022-11-04 關于Python?列表的索引取值問題_python
- 2022-09-21 flutter實現底部不規則導航欄_Android
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支