C# 中的 Foreach 和 Parallel.Foreach 有什么区别?
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 相比耗时更少。
广告