並行循環

並行庫(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)));
        }

 

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