1.在.net4.0中,有了一個新的類庫:任務並行庫。它極大地簡化了並行編程且內容豐富。這里僅介紹其中最簡單的
Parallel.For循環和Parallel.ForEach循環。它們位於System.Threading.Tasks命名空間。它們是兩個方法,這兩個方法將迭代分別放在不同的處理器上並行處理,如果機器是多處理器或多核處理器,這樣就會使性能大大提升。
2.例子用Parallel.For做計算,為數組賦值並打印,用Parallel.ForEach計算字符串數組每個元素的長度,運行結果:
3.代碼:
- using System;
- using System.Threading.Tasks; //必須使用這個命名空間
- namespace 為多核處理器而生的多線程方法Parallel.For和Parallel.ForEach
- {
- class Program
- {
- static void Main(string[] args)
- {
- Parallel.For(0,5,i=>Console.WriteLine("The square of {0} is {1}", i , i*i));
- Console.WriteLine();
- const int maxValues = 5;
- int[] squares=new int[maxValues];
- Parallel.For(0, maxValues,i=>Console.WriteLine(i*i));
- Console.WriteLine();
- string[] squarsStr = new string[]{
- "We","are","the","kings","of","this",
- "beautiful","world","How","do","you","think"
- };
- Parallel.ForEach(squarsStr,
- i => Console.WriteLine(string.Format("{0} has {1} letters",i,i.Length)));
- Console.WriteLine();
- }
- }
- }