如果您有一个要加速的foreach循环,并且不介意输出的顺序,则可以通过执行以下操作将其转换为并行的foreach循环:
using System; using System.Threading; using System.Threading.Tasks; public class MainClass { public static void Main() { int[] Numbers = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; // 单线程 Console.WriteLine("正常的foreach循环: "); foreach (var number in Numbers) { Console.WriteLine(longCalculation(number)); } // 这是并行(多线程解决方案) Console.WriteLine("并行的foreach循环: "); Parallel.ForEach(Numbers, number => { Console.WriteLine(longCalculation(number)); }); } private static int longCalculation(int number) { Thread.Sleep(1000); // 睡眠以模拟长时间计算 return number * number; } }