Parallel Processing with Parallel.ForEach
Parallel programming enhances application performance by harnessing multiple processor cores. Parallel.ForEach is a powerful construct that simplifies parallel processing in .NET applications.
Foreach Loop vs. Parallel.ForEach
The traditional foreach loop performs iterations sequentially on a single thread. Parallel.ForEach, on the other hand, distributes the workload across multiple threads, enabling simultaneous execution of iterations.
Characteristics of Foreach Loops:
Characteristics of Parallel.ForEach:
Converting to Parallel.ForEach
To convert the given code snippet to Parallel.ForEach:
Parallel.ForEach(list_lines, line => { // My Stuff });
Example
The following example demonstrates the difference between a foreach loop and Parallel.ForEach:
using System; using System.Diagnostics; using System.Collections.Generic; using System.Threading.Tasks; namespace ParallelForEachExample { class Program { static void Main() { var lines = File.ReadAllLines("proxylist.txt"); var list_lines = new List<string>(lines); Console.WriteLine("Traditional foreach loop"); var watch = Stopwatch.StartNew(); foreach (var line in list_lines) { Console.WriteLine(line); Thread.Sleep(10); } watch.Stop(); Console.WriteLine($"foreach loop execution time: {watch.ElapsedMilliseconds} ms"); Console.WriteLine("Using Parallel.ForEach"); watch = Stopwatch.StartNew(); Parallel.ForEach(list_lines, line => { Console.WriteLine(line); Thread.Sleep(10); }); watch.Stop(); Console.WriteLine($"Parallel.ForEach() execution time: {watch.ElapsedMilliseconds} ms"); } } }
Output
The output will demonstrate that Parallel.ForEach executes the iterations in parallel, reducing the overall processing time compared to the traditional foreach loop.
The above is the detailed content of How Does Parallel.ForEach Improve Performance Compared to a Traditional Foreach Loop in .NET?. For more information, please follow other related articles on the PHP Chinese website!