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