C#多线程 为多核处理器而生的多线程方法Parallel.For和Parallel.ForEach

1.在.net4.0中,有了一个新的类库:任务并行库。它极大地简化了并行编程且内容丰富。这里仅介绍其中最简单的

Parallel.For循环和Parallel.ForEach循环。它们位于System.Threading.Tasks命名空间。它们是两个方法,这两个方法将迭代分别放在不同的处理器上并行处理,如果机器是多处理器或多核处理器,这样就会使性能大大提升。

2.例子用Parallel.For做计算,为数组赋值并打印,用Parallel.ForEach计算字符串数组每个元素的长度,运行结果:

3.代码:

 

[csharp] view plain copy
 
  1. using System;  
  2. using System.Threading.Tasks; //必须使用这个命名空间  
  3.   
  4. namespace 为多核处理器而生的多线程方法Parallel.For和Parallel.ForEach  
  5. {  
  6.     class Program  
  7.     {  
  8.         static void Main(string[] args)  
  9.         {  
  10.             Parallel.For(0,5,i=>Console.WriteLine("The square of {0} is {1}", i , i*i));  
  11.             Console.WriteLine();  
  12.   
  13.             const int maxValues = 5;  
  14.             int[] squares=new int[maxValues];  
  15.             Parallel.For(0, maxValues,i=>Console.WriteLine(i*i));  
  16.             Console.WriteLine();  
  17.   
  18.             string[] squarsStr = new string[]{  
  19.                 "We","are","the","kings","of","this",  
  20.                 "beautiful","world","How","do","you","think"  
  21.             };  
  22.             Parallel.ForEach(squarsStr,   
  23.                 i => Console.WriteLine(string.Format("{0} has {1} letters",i,i.Length)));  
  24.             Console.WriteLine();  
  25.         }  
  26.     }  
  27. }  
 
 

posted on 2017-06-09 09:12  alex5211314  阅读(1824)  评论(0编辑  收藏  举报

导航