zoukankan      html  css  js  c++  java
  • 并行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();
            }
        }
    }

  • 相关阅读:
    List注意点【修改】
    最近遇到的笔试面试题(3)
    关于阅读
    各种语言
    最近遇到的笔试面试题(2)
    最近遇到的笔试面试题(1)
    5自由落体运动
    4 1000以内完数
    3水仙花数
    判断101-200之间的素数
  • 原文地址:https://www.cnblogs.com/MrZheng/p/10839781.html
Copyright © 2011-2022 走看看