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

C#多线程 为多核处理器而生的多线程方法Parallel.For和Parallel.ForEach
1.在.net4.0中,有了一个新的类库:任务并行库。它极大地简化了并行编程且内容丰富。这里仅介绍其中最简单的

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

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

C#多线程 替多核处理器而生的多线程方法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();
        }
    }
}