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个数字出现的顺序可能会不一样。

原文地址:https://www.cnblogs.com/OpenCoder/p/9802437.html