/// <summary> /// use ConcurrectCollection /// </summary> public void Run3() { var products = GetProducts(); BlockingCollection <NewProduct> newProducts = new BlockingCollection <NewProduct>(); Console.WriteLine("來源資料筆數:{0}", products.Count()); Console.WriteLine("執行前結果資料筆數:{0}", newProducts.Count()); var watch = new Stopwatch(); watch.Start(); Parallel.ForEach(products, x => { int id = x.Id; string name = x.Name; int stock = 100 + x.Id; var newProduct = new NewProduct() { Id = id, Name = name, Stock = stock }; newProducts.Add(newProduct); }); watch.Stop(); Console.WriteLine("Consume Time: {0} ms", watch.ElapsedMilliseconds); Console.WriteLine("執行後結果資料筆數:{0}", newProducts.Count()); }
/// <summary> /// 使用一般List會造成資料遺漏問題 /// </summary> public void Run() { var products = GetProducts(); List <NewProduct> newProducts = new List <NewProduct>(); Console.WriteLine("來源資料筆數:{0}", products.Count()); Console.WriteLine("執行前結果資料筆數:{0}", newProducts.Count()); Parallel.ForEach(products, x => { int id = x.Id; string name = x.Name; int stock = 100 + x.Id; var newProduct = new NewProduct() { Id = id, Name = name, Stock = stock }; newProducts.Add(newProduct); }); Console.WriteLine("執行後結果資料筆數:{0}", newProducts.Count()); }