/// <summary>
        ///该实现方式并不是最高效的
        ///只是举个例子,说明用锁来保护共享状态
        /// </summary>
        /// <param name="values"></param>
        /// <returns></returns>
        static int ParallelSum(IEnumerable<int> values)
        {
            object mutex = new object();
            int result = 0;
            Parallel.ForEach(
                source: values,
                localInit: () => 0,
                body: (item, state, localValue) => localValue + item,
                localFinally: lovalValue =>
                {
                    lock (mutex)
                    result += lovalValue;
                }
                );
            return result;
        }
   static int ParallelSum2(IEnumerable<int> values)
        {
            return values.AsParallel().Aggregate(seed: 0, func: (sum, item) => sum + item);
        }         static int ParallelSum1(IEnumerable<int> values)
        {
            return values.AsParallel().Sum();
        }
    static void Main(string[] args)
        {             for (int i = 0; i < 10; i++)
            {
                int[] nums = { 1, 23, 12, 31, 23, 12, 312, 3, 123, 12, 3 };
                Stopwatch sw = new Stopwatch();
                sw.Start();
                Console.WriteLine("ParallelSum:" + ParallelSum(nums));
                sw.Stop();
                TimeSpan ts = sw.Elapsed;
                Console.WriteLine(ts.TotalMilliseconds);                 Stopwatch sw1 = new Stopwatch();
                sw1.Start();
                Console.WriteLine("ParallelSum1:" + ParallelSum1(nums));
                sw1.Stop();
                TimeSpan ts1 = sw1.Elapsed;
                Console.WriteLine(ts1.TotalMilliseconds);                 Stopwatch sw2 = new Stopwatch();
                sw2.Start();
                Console.WriteLine("ParallelSum2:" + ParallelSum2(nums));
                sw2.Stop();
                TimeSpan ts2 = sw2.Elapsed;
                Console.WriteLine(ts2.TotalMilliseconds);             }
        }

      C#并行-LMLPHP

    总结:

     第一次运行:ParallelSum2 比 ParallelSum1 ParallelSum 快几倍左右

     第二次开始:ParallelSum2总体比ParallelSum1 ParallelSum快

     所以运用Aggregate()聚合功能 good

05-11 14:59