12/27/2022 11:14:56 PM

Run parallel loops and parallel async loops in .NET.

int counter = 0; ParallelOptions parallel_options = new() { MaxDegreeOfParallelism = 3 }; //for counter = 0; Console.WriteLine("Parallel.For"); //parantheses around "index"/(index) are optional Parallel.For(0, list.Count, parallel_options, (index) => { ProcessSync(list[index]); var progress = System.Threading.Interlocked.Increment(ref counter); Console.WriteLine(progress + "/" + list.Count); }); //foreach sync counter = 0; Console.WriteLine("Parallel.ForEach"); Parallel.ForEach(list, parallel_options, (item, token) => { ProcessSync(item); var progress = System.Threading.Interlocked.Increment(ref counter); Console.WriteLine(progress + "/" + list.Count); }); //foreach async counter = 0; Console.WriteLine("Parallel.ForEachAsync"); await Parallel.ForEachAsync(list, parallel_options, async (item, token) => { await ProcessAsync(item); var progress = System.Threading.Interlocked.Increment(ref counter); Console.WriteLine(progress + "/" + list.Count); });