使用AsParallel 进行并行化处理数据

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

namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {
            List<int> source = new List<int>();
            for (int i = 0; i < 1000; i++)
            {
                source.Add(i);
            }
            Stopwatch stop = new Stopwatch();
            stop.Start();
            var result = (from x in source.AsParallel().WithDegreeOfParallelism(50)
                         select proc(x)).ToList();
            Console.WriteLine(stop.Elapsed);

            stop.Stop();
            Console.Read();

        }
        public static int proc(int x) {
            Thread.Sleep(100);
            return 1;
        }
    }
}

  耗时12秒 不使用并行 耗时100秒

原文地址:https://www.cnblogs.com/ProDoctor/p/7110040.html