[Test] public void ParallelTets() { int processCount = Environment.ProcessorCount; Console.WriteLine($@"{nameof(Environment.ProcessorCount)} = {processCount}"); DataTable dataTable=new DataTable(); dataTable.Columns.Add("Id"); for (int i = 0; i < processCount * 10; i++) { DataRow dataRow = dataTable.NewRow(); dataRow["Id"] = i + 1; dataTable.Rows.Add(dataRow); } Stopwatch stopwatch = new Stopwatch(); stopwatch.Start(); foreach (DataRow row in dataTable.Rows) { Thread.Sleep(10); Console.Write($@"{row["Id"]},"); } Console.WriteLine(); stopwatch.Stop(); Console.WriteLine($@"No parallel takes {stopwatch.ElapsedMilliseconds} ms"); Console.WriteLine(); stopwatch.Reset(); stopwatch.Start(); Parallel.ForEach(dataTable.Rows.Cast<DataRow>(), row => { Thread.Sleep(10); Console.Write($@"{row["Id"]},"); }); Console.WriteLine(); stopwatch.Stop(); Console.WriteLine($@"With parallel takes {stopwatch.ElapsedMilliseconds} ms"); }
使用并行可能存在的问题,很重要
Potential Pitfalls in Data and Task Parallelism