并行循环

并行库(Task Parellel Library)是BCL中的一个类库,它极大地简化了并行编程,其中有俩个简单的结构为Parallel.ForParallel.ForEach循环,这俩个结构位于System.Threading.Tasks命名空间中。之前的for、foreach循环中,每一次迭代会依赖于之前那一次迭代的计算行为,而这俩个循环是迭代之间彼此独立,可以将不同的迭代放在不同的处理器上并行处理。

Parallel.For

该方法有12个重载,最简单的签名如下:

        static void Main(string[] args)
        {
            Parallel.For(0, 15, i => Console.WriteLine("The square of {0} is {1}", i, i * i));
        }
The square of 0 is 0
The square of 1 is 1
The square of 6 is 36
The square of 9 is 81
The square of 10 is 100
The square of 11 is 121
The square of 13 is 169
The square of 14 is 196
The square of 4 is 16
The square of 5 is 25
The square of 3 is 9
The square of 12 is 144
The square of 7 is 49
The square of 8 is 64
The square of 2 is 4

该程序满足各个迭代之间是相互独立的,并放在不同处理器上进行处理,所以不能确保迭代的执行次序。

Parallel.ForEach

该方法有相当多的重载,其中最简单的如下:

     static void Main(string[] args)
        {
            string[] squares = new string[]
            {
                "We","hold","these","truths","to"
            };
            Parallel.ForEach(squares, i => Console.WriteLine(string.Format("{0} has {1} letters", i, i.Length)));
        }

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章