Parallel.ForEach() 并行循环

现在的电脑几乎都是多核的,但在软件中并还没有跟上这个节奏,大多数软件还是采用传统的方式,并没有很好的发挥多核的优势。
微软的并行运算平台(Microsoft’s Parallel Computing Platform (PCP))提供了这样一个工具,让软件开发人员可以有效的使用多核提供的性能。
Parallel.ForEach()和Parallel.For()就是微软并发类的成员。
今天做了一个简单的测试,我的电脑是双核的,效果还是比较明显的。
一般的for和foreach循环用时都在10秒钟;并发for循环在0.5秒,并发foreach在0.1秒钟。
但是并发循环不能滥用,在简单的少次数循环下,并发循环可能会体现不出其优势。
下面是简单的测试代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;


namespace parallelForeach
{
    class Program
    {
        static void Main(string[] args)
        {
            DateTime startTime;
            TimeSpan resultTime;
            List<entityA> source = new List<entityA>();
            for (int i = 0; i < 100; i++)
            {
                source.Add(new entityA
                {
                    name = "悟空" + i,
                    sex = i % 2 == 0 ? "" : "",
                    age = i
                });
            }
            startTime = System.DateTime.Now;
            loop1(source);
            resultTime = System.DateTime.Now - startTime;
            Console.WriteLine("一般for循环耗时:" + resultTime);
            startTime = System.DateTime.Now;
            loop2(source);
            resultTime = System.DateTime.Now - startTime;
            Console.WriteLine("一般foreach循环耗时:" + resultTime);
            startTime = System.DateTime.Now;
            loop3(source);
            resultTime = System.DateTime.Now - startTime;
            Console.WriteLine("并行for循环耗时:" + resultTime.Milliseconds);
            startTime = System.DateTime.Now;
            loop4(source);
            resultTime = System.DateTime.Now - startTime;
            Console.WriteLine("并行foreach循环耗时:" + resultTime.Milliseconds);
            Console.ReadLine();
        }

//普通的for循环
        static void loop1(List<entityA> source)
        {
            int count = source.Count();
            for (int i = 0; i < count; i++)
            {
                System.Threading.Thread.Sleep(100);
            }
        }

//普通的foreach循环
        static void loop2(List<entityA> source)
        {
            foreach (entityA item in source)
            {
                System.Threading.Thread.Sleep(100);
            }
        }

//并行的for循环
        static void loop3(List<entityA> source)
        {
            int count = source.Count();
            Parallel.For(0, count, item =>
            {
                System.Threading.Thread.Sleep(100);
            });
        }

//并行的foreach循环
        static void loop4(List<entityA> source)
        {
            Parallel.ForEach(source, item =>
            {
                System.Threading.Thread.Sleep(100);
            });
        }
    }

//简单的实体
    class entityA
    {
        public string name { set; get; }
        public string sex { set; get; }
        public int age { set; get; }
    }
}
原文地址:https://www.cnblogs.com/hnsongbiao/p/4972615.html