.NET 4中并行编程的简单例子

本文介绍了一个使用C#并行编程技术处理图片的应用实例。通过Parallel.ForEach方法,实现了对指定文件夹下所有JPEG图片进行旋转翻转操作,并保存到新的目录中。此例展示了并行编程相较于传统多线程的优势。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

该文可参考 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
  
    source, Action
   
     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的优势。而之前的多线程其实是需要切换线程的。
 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值