.net 4.0 新特性 Linq 并行化处理

 //
        // 摘要:
        //     启用查询的并行化。
        //
        // 参数:
        //   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);

首先是测试结果:

测试代码如下2011012715513725.jpg2011012715532794.jpg

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;
        }

转载于:https://www.cnblogs.com/rosanshao/archive/2011/01/27/1946302.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值