Using multiple threads with Parallel LINQ
By default, only one thread is used to execute a LINQ query. Parallel LINQ (PLINQ) is an easy way to enable multiple threads to execute a query.
To see it in action, we will start with some code that only uses a single thread to double 200 million integers.
Add a new console application project named Ch09_PLINQ. Import the System.Diagnostics namespace and statically import the System.Console type.
Add the following statements to the Main method:
var watch = Stopwatch.StartNew();
Write("Press ENTER to start. ");
ReadLine();
watch.Start();
IEnumerable<int> numbers = Enumerable.Range(1, 200000000);
var squares = numbers.Select(number => number * 2).ToArray();
watch.Stop();
WriteLine($"{watch.ElapsedMilliseconds:#,##0} ellapsed milliseconds.");Press Ctrl + F5 to run the application, but do not press Enter yet.
Right-click on the Windows Taskbar or press Ctrl + Alt + Delete, and then click on Task Manager.
At the bottom of the Task Manager window,...