zoukankan      html  css  js  c++  java
  • .NET 4中并行编程的简单例子

    该文可参考 http://msdn.microsoft.com/en-us/library/dd460720(VS.100).aspx

    namespace ForEachDemo
    {
        using System;
        using System.Drawing; // requires system.Drawing.dll
        using System.IO;
        using System.Threading;
        using System.Threading.Tasks;
    
        class SimpleForEach
        {
            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)
                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);
                    System.Drawing.Bitmap bitmap = new System.Drawing.Bitmap(currentFile);
    
                    bitmap.RotateFlip(System.Drawing.RotateFlipType.Rotate180FlipNone);
                    bitmap.Save(System.IO.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
                     ); //close method invocation
    
                // Keep the console window open in debug mode.
                Console.WriteLine("Processing complete. Press any key to exit.");
                Console.ReadKey();
            }
        }
    }
    
    注意:
    并行编程与之前的多线程的区别,并行编程其实可以理解为多核编程,它可以更好地利用多CPU的优势。而之前的多线程其实是需要切换线程的。
     
  • 相关阅读:
    Linux 3.2中回写机制的变革
    Linux字符设备与块设备的区别与比较
    分布式文件系统:原理、问题与方法
    为什么说B+-tree比B 树更适合实际应用中操作系统的文件索引和数据库索引?
    Linux IO barrier
    磁盘IO:缓存IO与直接IO
    【珍藏】高性能IO模型浅析
    souretree+上面提交代码和gerrit上面出现Cannot+merge的时候的解决方法
    vscode快速生成自定义HTML模板
    在jq里面设置样式的高度height、设置隐藏和显示的小功能
  • 原文地址:https://www.cnblogs.com/chenxizhang/p/1713167.html
Copyright © 2011-2022 走看看