我对Parallel.ForEach有点困惑。 什么是平行。ForEach,它到底做什么? 请不要引用任何MSDN链接。

这里有一个简单的例子:

string[] lines = File.ReadAllLines(txtProxyListPath.Text);
List<string> list_lines = new List<string>(lines);

foreach (string line in list_lines)
{
    //My Stuff
}

我如何用Parallel.ForEach重写这个例子?


当前回答

var concurrentList = new ConcurrentBag<Dto>();
var opts = new ParallelOptions { MaxDegreeOfParallelism = Convert.ToInt32(Math.Ceiling((Environment.ProcessorCount * 0.65) * 1.0)) }; 

Parallel.ForEach(data,
                 opts,
                 row => {
                        var processResult = process each row    
                        concurrentList.Add(processResult);
                        }
                        );

其他回答

这些台词对我很管用。

string[] lines = File.ReadAllLines(txtProxyListPath.Text);
var options = new ParallelOptions { MaxDegreeOfParallelism = Environment.ProcessorCount * 10 };
Parallel.ForEach(lines , options, (item) =>
{
 //My Stuff
});

对于大文件,使用以下代码(您不太需要内存)

Parallel.ForEach(File.ReadLines(txtProxyListPath.Text), line => {
    //Your stuff
});
string[] lines = File.ReadAllLines(txtProxyListPath.Text);
List<string> list_lines = new List<string>(lines);
Parallel.ForEach(list_lines, line =>
{
    //Your stuff
});

Foreach循环:

迭代是按顺序进行的,一个接一个 foreach循环从单个线程运行。 foreach循环在.NET的每个框架中都有定义 慢进程的执行可能会更慢,因为它们是连续运行的 进程2在1完成之前不能启动。进程3不能启动,直到2和1完成… 快速进程的执行速度更快,因为没有线程开销

平行的。ForEach:

执行是平行进行的。 平行的。ForEach使用多线程。 平行的。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

使用并行。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
string[] lines = File.ReadAllLines(txtProxyListPath.Text);

// No need for the list
// List<string> list_lines = new List<string>(lines); 

Parallel.ForEach(lines, line =>
{
    //My Stuff
});

这将导致在循环中并行地解析行。如果您想要更详细、更少“面向引用”的Parallel类介绍,我写了一个关于TPL的系列文章,其中包含了关于Parallel. foreach的部分。