新建一個.NET Core控制檯程序,代碼以下:spa
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(); } } }
執行後結果以下:3d
由於Parallel.ForEach爲並行執行,因此再次執行時6個數字出現的順序可能會不同。code