我有点困惑
Parallel.ForEach
。Parallel.ForEach
是什么?它到底有什么作用?这是一个简单的例子:
string[] lines = File.ReadAllLines(txtProxyListPath.Text);
List<string> list_lines = new List<string>(lines);
foreach (string line in list_lines)
{
//My Stuff
}
如何用
Parallel.ForEach
重写这个示例?
Foreach 循环:
- 迭代按顺序进行,一个接一个
- foreach 循环是从单个线程运行的。
- foreach 循环在 .NET 的每个框架中都有定义
- 执行慢进程可能会更慢,因为它们是串行运行的
- 进程 2 必须在进程 1 完成后才能启动。流程 3 必须在流程 2 和流程 1 完成后才能开始...
- 执行快速进程可以更快,因为没有线程开销
并行。ForEach:
的区别 Parallel.ForEach() 示例下面的例子清楚地展示了传统 foreach 循环和
- 执行以并行方式进行。
- Parallel.ForEach 使用多个线程。
- Parallel.ForEach 在 .Net 4.0 及以上框架中定义。
- 执行慢进程可以更快,因为它们可以并行运行
由于额外的线程开销,
- 进程 1、2 和 3 可以同时运行(请参阅下面示例中的重用线程)
- 快速进程的执行可能会较慢
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
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
Parallel.ForEach(File.ReadLines(txtProxyListPath.Text), line => {
//Your stuff
});
这些行对我有用。
string[] lines = File.ReadAllLines(txtProxyListPath.Text);
var options = new ParallelOptions { MaxDegreeOfParallelism = Environment.ProcessorCount * 10 };
Parallel.ForEach(lines , options, (item) =>
{
//My Stuff
});
我想补充一下并行选项。如果您没有提及,默认情况下所有 RAM 将被用于此目的,这可能会给您带来生产问题。因此最好在代码中添加最大并行度。
Parallel.ForEach(list_lines, new ParallelOptions { MaxDegreeOfParallelism = 2 }, line =>
{
});