. NET parallel and multi-thread Learning Series 1. net parallel Multithreading
Series 1 of parallel and multi-thread Learning
I. Parallel preliminary test:
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 }
Call:
1 static void Main (string [] args) 3 {5 Stopwatch sw = new Stopwatch (); 7 sw. start (); 9 // serial execution: 11 test (); 13 test1 (); 15 // parallel execution: 17Parallel. invoke (test, test1); 19sw. stop (); 21Console. writeLine ("Total time consumption:"); 23Console. writeLine (sw. elapsedMilliseconds/1000 + "s"); 25}
Ii. Parallel partitioning:
1 Parallel. forEach (Partitioner. create (, 5), (x, s) => {3 // custom serial in parallel code. The third parameter indicates the range between item1 and 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 (); // very similar to the break20 if (s. shouldExitCurrentIteration) 22 return; 24 });
3. Exception Capture: aggresponexception
1 int [] arry = new int [10001]; 2 3 for (int I = 0; I <10000; I ++) 5 {7 arry [I] = I; 9} 11 try13 {14 15 Parallel. forEach (arry, (x, s) => 17 {19 Console. writeLine (x); 21 if (sw. elapsed. seconds> 3) 23 {25 throw new TimeoutException ("Operation Time-out"); 27} 29}); 31} 33 catch (aggresponexception ex) 35 {39 foreach (var item in ex. innerExceptions) 41 {43 Console. writeLine (item); 45} 47}
4. Specify parallel scheduling:
1 ParallelOptions options = new ParallelOptions (); 3 options. maxDegreeOfParallelism = 1; // If set to 1, it is similar to executing 5 options in sequence in serial code. maxDegreeOfParallelism = Environment. processorCount; // obtain the number of processors on the computer 7 Parallel. for (1, 10, options, (x) => 9 {11 Console. writeLine (x); 13 });
5. To be continued...