并行与多线程学习系列一
一、并行初试:
1 public static void test() 3 { 5 for (int i = 0; i < 10000; i++) 7 { 9 Console.WriteLine(i); 11 } 13 } 14 15 public static void test1() 17 { 19 for (int i = 0; i < 10000; i++) 21 { 23 Console.WriteLine(i + "aaaaaaaaaaaaaaa"); 25 } 27 }
调用:
1 static void Main(string[] args) 3 { 5 Stopwatch sw = new Stopwatch(); 7 sw.Start(); 9 //串行执行: 11 test(); 13 test1(); 15 //并行执行: 17Parallel.Invoke(test, test1); 19sw.Stop(); 21Console.WriteLine("共耗费时间:"); 23Console.WriteLine(sw.ElapsedMilliseconds / 1000+"s"); 25 }
二、分区并行:
1 Parallel.ForEach(Partitioner.Create(1,20,5),(x,s)=>{ 3 //并行代码中自定义串行,第三个参数表示item1到item2之间的范围
6 Console.WriteLine(x); 8 for (int i = x.Item1; i < x.Item2; i++) 10 { 12 if (i == 10) break; 13 14 Console.WriteLine(i); 16 } 18 s.Break();// 非常类似普通for循环中的break 20 if (s.ShouldExitCurrentIteration) 22 return; 24 });
三、异常捕获:AggregateException
1 int[] arry = new int[10001]; 2 3 for (int i = 0; i < 10000; i++) 5 { 7 arry[i] = i; 9 } 11 try 13 { 14 15 Parallel.ForEach(arry, (x, s) => 17 { 19 Console.WriteLine(x); 21 if (sw.Elapsed.Seconds > 3) 23 { 25 throw new TimeoutException("操作超时"); 27 } 29 }); 31 } 33 catch (AggregateException ex) 35 { 39 foreach (var item in ex.InnerExceptions) 41 { 43 Console.WriteLine(item); 45 } 47 }
四、指定并行调度:
1 ParallelOptions options = new ParallelOptions(); 3 options.MaxDegreeOfParallelism = 1;//如果设置为1就类似于串行代码按顺序执行 5 options.MaxDegreeOfParallelism =Environment.ProcessorCount;//获取计算机上面的处理器数量 7 Parallel.For(1,10,options,(x) => 9 { 11 Console.WriteLine(x); 13 });
五、未完待续...