新建一個.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個數字出現的順序可能會不一樣。