並行與多線程學習系列一
一、並行初試:
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 });
五、未完待續...