我们循环大多数是用的foreach,这种方法是串行,也就是单线程,而Parallel.ForEach指的是并行,也就是多线程。
在循环迭代时,并不是用并行时间越短,下面是一个测试实例,分别用串行和并行循环150W条数据
using System; using System.Collections; using System.Collections.Concurrent; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Threading.Tasks; namespace ConsoleApp2 { class Program { static void Main(string[] args) { ConcurrentBag<Stu> conStu = new ConcurrentBag<Stu>(); ConcurrentBag<Stu> conStu2 = new ConcurrentBag<Stu>(); int num = 1500000;//150万 //获取集合 var lst = GetStu(num); #region 串行循环 var watch = new Stopwatch(); watch.Start(); foreach (var item in lst) { conStu.Add(item); } watch.Stop(); var completeRequest = watch.ElapsedMilliseconds; Console.WriteLine($"\n\nForeach {num.ToString("N0")} 使用时间(毫秒):{completeRequest}"); Console.WriteLine($"conStu 集合*:{conStu.Count + 1}条"); #endregion #region 并行循环 var watch2 = new Stopwatch(); watch2.Start(); ParallelLoopResult result = Parallel.ForEach(lst, new ParallelOptions { MaxDegreeOfParallelism = Environment.ProcessorCount }, item => { conStu2.Add(item); }); watch2.Stop(); var completeRequest2 = watch2.ElapsedMilliseconds; Console.WriteLine($"\n\n Parallel.ForEach {num.ToString("N0")} 使用时间(毫秒):{completeRequest2}"); Console.WriteLine($"conStu2 集合*:{conStu2.Count + 1}条"); #endregion } public static List<Stu> GetStu(int num) { List<Stu> lstStu = new List<Stu>(); for (int i = 1; i < num; i++) { Stu sModle = new Stu(); sModle.Id = i; sModle.uName = "测试" + i; lstStu.Add(sModle); } return lstStu; } } public class Stu { public int Id { get; set; } public String uName { get; set; } } }
测试了3次,但结果还是用串行时间会少些