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

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            List<int> aa = new List<int>();
            Random Rand = new Random();
            for (int i = 0; i < 10000000; i++)
            {
                aa.Add(Rand.Next(1000));
            }
            Stopwatch st = new Stopwatch();

            st.Start();
            foreach (var item in aa)
            {
                item.ToString();
            }
            st.Stop();
            Console.WriteLine("========" + st.ElapsedMilliseconds);

            st.Restart();
            Parallel.ForEach(aa, (item, loopstate) => { item.ToString(); });
            st.Stop();
            Console.WriteLine("========" + st.ElapsedMilliseconds);

            st.Restart();
            Parallel.ForEach(aa, new ParallelOptions() { MaxDegreeOfParallelism = 2},(item, loopstate) => { item.ToString(); }); //指定最大线程数
            st.Stop();
            Console.WriteLine("========" + st.ElapsedMilliseconds);

            st.Restart();
            Parallel.ForEach(aa, (item, loopstate) => {
                item.ToString();
                if (item>900)
                {
                    loopstate.Stop();
                }
                if (loopstate.IsStopped)
                {
                    Console.WriteLine("loopstate.IsStopped");
                }
            });
            st.Stop();
            Console.WriteLine("========" + st.ElapsedMilliseconds);
            Console.Read();
        }
    }
}

 并行forearch的使用及测试(Parallel.Foreach) 随笔

 

SRE实战 互联网时代守护先锋,助力企业售后服务体系运筹帷幄!一键直达领取阿里云限量特价优惠。
扫码关注我们
微信号:SRE实战
拒绝背锅 运筹帷幄