点关注不迷路

Max

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

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();
        }
    }
}

 

posted @ 2019-05-09 17:27  Max麦克斯  阅读(752)  评论(2编辑  收藏  举报