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. }  
 
 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM