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