C# 并行运算

今天被派到其他组做临时支援,看到了Parallel。百度了下原来是做并行计算的。支援完毕后,自己了解了下,感觉C#提供的并行运算在使用形式上跟JQuery的$.each()有点类似。
Parallel.For(迭代系列的第一个参数,迭代系列最后一个索引值+1,在每个迭代参数中执行的委托)

1 static void Main(string[] args)
2 {
3     Parallel.For(0, 15, i => Console.WriteLine("第{0}个i", i));
4 
5     Console.ReadKey();
6 }

 1 static void Main(string[] args)
 2 {
 3     int arraySquare = 20;
 4     int[] array = new int[arraySquare];
 5     Parallel.For(0, arraySquare, i => array[i] = i * i);
 6     foreach (int item in array)
 7     {
 8         Console.WriteLine(item);
 9     }
10 
11     Console.ReadKey();
12 }

----------------------------------------------------

Parallel.ForEach<迭代运算的每个元素数据类型>(要进行迭代运算的数据集合,要应用到集合中每个元素的Lambda表达式/委托/方法)

1 static void Main(string[] args)
2 {
3     int[] arrNew = { 1, 2, 3, 4, 5, 6, 7 };
4 
5     Parallel.ForEach(arrNew, i => { Console.WriteLine(i * i); });
6 
7     Console.ReadKey();
8 }

-----------------------------------------------------------

无意中犯了一个错误,不过歪打正着,正好证明Parallel是多核执行的

 1 static void Main(string[] args)
 2 {
 3     int[] arrNew = { 1, 2, 3, 4, 5, 6, 7 };
 4     Parallel.ForEach(arrNew, i => { GetArrayResult(arrNew); });
 5     Console.ReadKey();
 6 }
 7 public static void GetArrayResult(int[] array)
 8 {
 9     for (int i = 0; i < array.Length; i++)
10     {
11         Console.WriteLine(string.Format("第{0}个索引数值是{1}", i, array[i]));
12     }
13 
14 }

原文地址:https://www.cnblogs.com/sunice/p/6486498.html