Parallel.ForEach使用示例


新建一個.NET Core控制台程序,代碼如下:

using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;

namespace NetCoreParallel
{
    class Program
    {
        static void Main(string[] args)
        {
            var numbersToShow = new List<int>() { 1, 2, 3, 4, 5, 6 };

            Parallel.ForEach(numbersToShow, number => 
            {
                Thread.Sleep(3000);

                Console.WriteLine($"Parallel ForEach is now displaying number: {number.ToString()}");
            });
            Console.WriteLine();
            Console.WriteLine();
            
            Console.WriteLine("Parallel ForEach finished.");
            Console.WriteLine("Press key contiune...");
            Console.ReadKey();
        }
    }
}

執行后結果如下:

因為Parallel.ForEach為並行執行,所以再次執行時6個數字出現的順序可能會不一樣。

 


免責聲明!

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



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