using System.Collections.Generic;
using System.Threading.Tasks;
private static IList<int> items = new []{ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
private static int _millisecondsDelay = 500;
public static void Main()
private static void RunNormalForEach()
Console.WriteLine($"In Normal foreach:{Environment.NewLine}");
var timerNormal = System.Diagnostics.Stopwatch.StartNew();
foreach (var item in items)
System.Threading.Thread.Sleep(_millisecondsDelay);
Console.WriteLine($"foreach Elapsed (s): {timerNormal.Elapsed.TotalSeconds:N2}");
private static void RunParallelForEach()
Console.WriteLine($"In Parallel.ForEach:{Environment.NewLine}");
var timerParallel = System.Diagnostics.Stopwatch.StartNew();
Parallel.ForEach(items, item =>
System.Threading.Thread.Sleep(_millisecondsDelay);
Console.WriteLine($"Parallel.ForEach Elapsed (s): {timerParallel.Elapsed.TotalSeconds:N2}");
private static void LogItemAndThread(int item)
var threadId = Thread.CurrentThread.ManagedThreadId.ToString().PadRight(4, ' ');
Console.WriteLine($"ManagedThreadId {threadId}: {item}");