C#中的Foreach循环在单个线程上运行,并且处理过程是一个接一个地进行的。C#中的Parallel.Foreach循环在多个线程上运行,并且处理以并行方式进行。这意味着它可以一次浏览所有项目,而无需等待上一个项目完成。
Parallel.Foreach的执行比正常的ForEach更快。要使用Parallel.ForEach循环,我们需要导入System.Threading.Tasks命名空间。
using System; using System.Collections.Generic; using System.Diagnostics; using System.Threading; using System.Threading.Tasks; namespace DemoApplication{ class Demo{ static void Main(string[] args){ var animals = new List<string>{ "cat", "rat", "deer", "elephant", "lion", "tiger", "dog", "pig", "buffalo", "rabbit", "horse", "cheetah", "cow", "goat", "sheep", "donkey", "zebra", "wolf", "fox", "lepoard", "monkey", "kangaroo", "girafee", "hippo" }; var stopWatch = Stopwatch.StartNew(); foreach (string animal in animals){ Console.WriteLine($"Fruit Name: {animal}, Thread Id={Thread.CurrentThread.ManagedThreadId}"); } Console.WriteLine($"foreach loop execution time = {stopWatch.Elapsed.TotalSeconds} seconds"); var stopWatch2 = Stopwatch.StartNew(); Parallel.ForEach(animals, animal =>{ Console.WriteLine($"Fruit Name: {animal}, Thread Id={Thread.CurrentThread.ManagedThreadId}"); }); Console.WriteLine($"Parallel foreach loop execution time = {stopWatch2.Elapsed.TotalSeconds} seconds"); Console.ReadLine(); } } }
输出结果
上面代码的输出是
Fruit Name: cat, Thread Id= 1 Fruit Name: rat, Thread Id= 1 Fruit Name: deer, Thread Id= 1 Fruit Name: elephant, Thread Id= 1 Fruit Name: lion, Thread Id= 1 Fruit Name: tiger, Thread Id= 1 Fruit Name: dog, Thread Id= 1 Fruit Name: pig, Thread Id= 1 Fruit Name: buffalo, Thread Id= 1 Fruit Name: rabbit, Thread Id= 1 Fruit Name: horse, Thread Id= 1 Fruit Name: cheetah, Thread Id= 1 Fruit Name: cow, Thread Id= 1 Fruit Name: goat, Thread Id= 1 Fruit Name: sheep, Thread Id= 1 Fruit Name: donkey, Thread Id= 1 Fruit Name: zebra, Thread Id= 1 Fruit Name: wolf, Thread Id= 1 Fruit Name: fox, Thread Id= 1 Fruit Name: lepoard, Thread Id= 1 Fruit Name: monkey, Thread Id= 1 Fruit Name: kangaroo, Thread Id= 1 Fruit Name: girafee, Thread Id= 1 Fruit Name: hippo, Thread Id= 1 foreach loop execution time = 0.0129221 seconds Fruit Name: cat, Thread Id= 1 Fruit Name: rat, Thread Id= 1 Fruit Name: deer, Thread Id= 1 Fruit Name: elephant, Thread Id= 1 Fruit Name: lion, Thread Id= 1 Fruit Name: tiger, Thread Id= 1 Fruit Name: pig, Thread Id= 1 Fruit Name: buffalo, Thread Id= 1 Fruit Name: dog, Thread Id= 3 Fruit Name: sheep, Thread Id= 3 Fruit Name: donkey, Thread Id= 3 Fruit Name: rabbit, Thread Id= 1 Fruit Name: goat, Thread Id= 5 Fruit Name: fox, Thread Id= 5 Fruit Name: lepoard, Thread Id= 5 Fruit Name: cow, Thread Id= 4 Fruit Name: hippo, Thread Id= 4 Fruit Name: kangaroo, Thread Id= 9 Fruit Name: girafee, Thread Id= 6 Fruit Name: monkey, Thread Id= 5 Fruit Name: horse, Thread Id= 1 Fruit Name: cheetah, Thread Id= 1 Fruit Name: zebra, Thread Id= 3 Fruit Name: wolf, Thread Id= 3 Parallel foreach loop execution time = 0.0092988 seconds
从上面的结果中我们可以看到,Parallel.Foreach在不同的线程中执行,并且比普通的foreach花费的时间更少。