Plinq-Parallel.ForEach for 性能提升

https://msdn.microsoft.com/zh-cn/library/dd460720.aspx

 

本示例显示如何使用 Parallel.ForEach 循环对任何 System.Collections.IEnumerable 或 System.Collections.Generic.IEnumerable<T> 数据源启用数据并行。

System_CAPS_note注意

本文档使用 lambda 表达式在 PLINQ 中定义委托。  如果您不熟悉 C# 或 Visual Basic 中的 lambda 表达式,请参见 Lambda Expressions in PLINQ and TPL。  

示例

 
//
// IMPORTANT!!!: Add a reference to System.Drawing.dll
using System;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using System.Drawing;

public class Example
{
    public static void Main()
    {
        // A simple source for demonstration purposes. Modify this path as necessary.
        String[] files = System.IO.Directory.GetFiles(@"C:\Users\Public\Pictures\Sample Pictures", "*.jpg");
        String newDir = @"C:\Users\Public\Pictures\Sample Pictures\Modified";
        System.IO.Directory.CreateDirectory(newDir);

        // Method signature: Parallel.ForEach(IEnumerable<TSource> source, Action<TSource> body)
        // Be sure to add a reference to System.Drawing.dll.
        Parallel.ForEach(files, (currentFile) => 
                                {
                                    // The more computational work you do here, the greater 
                                    // the speedup compared to a sequential foreach loop.
                                    String filename = System.IO.Path.GetFileName(currentFile);
                                    var bitmap = new Bitmap(currentFile);

                                    bitmap.RotateFlip(RotateFlipType.Rotate180FlipNone);
                                    bitmap.Save(Path.Combine(newDir, filename));

                                    // Peek behind the scenes to see how work is parallelized.
                                    // But be aware: Thread contention for the Console slows down parallel loops!!!

                                    Console.WriteLine("Processing {0} on thread {1}", filename, Thread.CurrentThread.ManagedThreadId);
                                    //close lambda expression and method invocation
                                });


        // Keep the console window open in debug mode.
        Console.WriteLine("Processing complete. Press any key to exit.");
        Console.ReadKey();
    }
}
下面设置了最大的并发线程数
private static void TParllel()
        {
            var list = new List<int>(16000);

            for (int i = 0; i < 16000; i++)
            {
                list.Add(i);
            }
            Parallel.ForEach(list, new ParallelOptions { MaxDegreeOfParallelism = 200}, (p, state) => { Invoke(p); });
        }

http://www.cnblogs.com/huangxincheng/archive/2012/04/02/2429543.html

posted @ 2016-05-12 11:11  yuan.net  阅读(378)  评论(0编辑  收藏  举报