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

2019/05/09 17:27
阅读数 22
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();
        }
    }
}

 

展开阅读全文
打赏
0
0 收藏
分享
加载中
更多评论
打赏
0 评论
0 收藏
0
分享
返回顶部
顶部