using System.Collections.Concurrent; using System.Diagnostics; namespace ConsoleApp85 { internal class Program { static void Main(string[] args) { try { Stopwatch watch = new Stopwatch(); Console.WriteLine("AddModelSequential started!"); watch.Start(); AddModelSequential(10000000); watch.Stop(); Console.Error.WriteLine($"AddModelSequential cost:{watch.ElapsedMilliseconds} milliseconds!\n\n\n"); Console.Error.WriteLine("AddModelParallel() started!"); watch.Restart(); AddModelParallel(10000000); watch.Stop(); Console.Error.WriteLine($"AddModelParallel() cost {watch.ElapsedMilliseconds} milliseconds!"); } catch (Exception ex) { Console.Error.WriteLine(ex.Message); Console.Error.WriteLine(ex.StackTrace.ToString()); } Console.ReadLine(); } static List<dynamic> AddModelSequential(int modelsCount) { var list=new List<dynamic>(); for(int i=0;i<modelsCount;i++) { int f = 0; for (int j = 0; j < 5000; j++) { f++; } list.Add(new { bbb = i, aaa = "1", ccc = f }); } return list; } static ConcurrentBag<dynamic> AddModelParallel(int modelsCount) { var list=new ConcurrentBag<dynamic>(); Parallel.For(0, modelsCount, x => { int f = 0; for(int j=0;j<5000;j++) { f++; } list.Add(new { bbb = x, aaa = "a", ccc = f }); }); return list; } } }
标签:ConcurrentBag,Console,C#,watch,int,WriteLine,Error,AddModelSequential,Parallel From: https://www.cnblogs.com/Fred1987/p/18434549