Foreach 循环:
- 迭代是按顺序进行的,一个接一个
- foreach 循环从单个线程运行。
- foreach 循环在 .NET 的每个框架中都有定义
- 慢速进程的执行可能会更慢,因为它们是串行运行的
- 进程 2 在 1 完成之前无法启动。过程 3 无法启动,直到 2 和 1 完成...
- 快速进程的执行可以更快,因为没有线程开销
Parallel.ForEach:
- 执行以并行方式进行。
- Parallel.ForEach 使用多个线程。
- Parallel.ForEach 在 .Net 4.0 及以上框架中定义。
- 慢进程的执行可以更快,因为它们可以并行运行。
- 进程 1、2 和 3可以同时运行(参见下面的示例中的重用线程)
- 由于额外的线程开销,快速进程的执行可能会更慢。
下面的例子清楚地展示了传统 foreach 循环和
Parallel.ForEach() 示例
using System;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
namespace ParallelForEachExample
{
class Program
{
static void Main()
{
string[] colors = {
"1. Red",
"2. Green",
"3. Blue",
"4. Yellow",
"5. White",
"6. Black",
"7. Violet",
"8. Brown",
"9. Orange",
"10. Pink"
};
Console.WriteLine("Traditional foreach loop\n");
//start the stopwatch for "for" loop
var sw = Stopwatch.StartNew();
foreach (string color in colors)
{
Console.WriteLine("{0}, Thread Id= {1}", color, Thread.CurrentThread.ManagedThreadId);
Thread.Sleep(10);
}
Console.WriteLine("foreach loop execution time = {0} seconds\n", sw.Elapsed.TotalSeconds);
Console.WriteLine("Using Parallel.ForEach");
//start the stopwatch for "Parallel.ForEach"
sw = Stopwatch.StartNew();
Parallel.ForEach(colors, color =>
{
Console.WriteLine("{0}, Thread Id= {1}", color, Thread.CurrentThread.ManagedThreadId);
Thread.Sleep(10);
}
);
Console.WriteLine("Parallel.ForEach() execution time = {0} seconds", sw.Elapsed.TotalSeconds);
Console.Read();
}
}
}
输出
Traditional foreach loop
1. Red, Thread Id= 10
2. Green, Thread Id= 10
3. Blue, Thread Id= 10
4. Yellow, Thread Id= 10
5. White, Thread Id= 10
6. Black, Thread Id= 10
7. Violet, Thread Id= 10
8. Brown, Thread Id= 10
9. Orange, Thread Id= 10
10. Pink, Thread Id= 10
foreach loop execution time = 0.1054376 seconds
使用 Parallel.ForEach 示例
1. Red, Thread Id= 10
3. Blue, Thread Id= 11
4. Yellow, Thread Id= 11
2. Green, Thread Id= 10
5. White, Thread Id= 12
7. Violet, Thread Id= 14
9. Orange, Thread Id= 13
6. Black, Thread Id= 11
8. Brown, Thread Id= 10
10. Pink, Thread Id= 12
Parallel.ForEach() execution time = 0.055976 seconds