//
        // 摘要:
        //     启用查询的并行化。
        //
        // 参数:
        //   source:
        //     要转换为 System.Linq.ParallelQuery<TSource> 的 System.Collections.Generic.IEnumerable<T>。
        //
        // 类型参数:
        //   TSource:
        //     source 中的元素的类型。
        //
        // 返回结果:
        //     作为要绑定到 ParallelEnumerable 扩展方法的 System.Linq.ParallelQuery<TSource> 的源。
        //
        // 异常:
        //   System.ArgumentNullException:
        //     source 是 null 引用(在 Visual Basic 中为 Nothing)。
        public static ParallelQuery<TSource> AsParallel<TSource>(this IEnumerable<TSource> source);

首先是测试结果:

测试代码如下

static void Main(string[] args)
        {
            IEnumerable<int> numbers = Enumerable.Range(1, 1000);

            // Remove AsParallel() Method in PLINQ query to see the difference in speed
            IEnumerable<int> results = from n in numbers.AsParallel() //并行化计算 from n in numbers 非并行化计算
                                       where IsDivisibleByFive(n)
                                       select n;

            Stopwatch sw = Stopwatch.StartNew();
            IList<int> resultsList = results.ToList();
            Console.WriteLine("{0} items", resultsList.Count());
            sw.Stop();

            Console.WriteLine("It Took {0} ms", sw.ElapsedMilliseconds);

            Console.WriteLine("\nFinished...");
            Console.ReadKey(true);
        }

        static bool IsDivisibleByFive(int i)
        {
            Thread.SpinWait(2000000);
            return i % 5 == 0;
        }

posted on 2011-01-27 15:55  rosanshao  阅读(750)  评论(0编辑  收藏  举报