并行Linq-创新互联
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Collections.Concurrent; using System.Threading; using System.Diagnostics; namespace ConsoleApplication5 { class Program { static void Main(string[] args) { //并行LINQ //****************************************************** //测试时间 Stopwatch sw = Stopwatch.StartNew(); long l = sw.ElapsedMilliseconds; //****************************************************** const int maxsize = 100000000; var data = new int[maxsize]; Random ran = new Random(); for (int i = 0; i < maxsize; i++) { checked { data[i] = ran.Next(40); } } //===========================================并行查询 //AsParallel() 启用查询的并行化 //AsParallel() 返回ParallelQuery,所以Where()、Select()等方法不在返回IEnumerable ,而返回ParallelQuery var query = (from r in data.AsParallel() select r).Take(20).Select(r => r); Foreach(query); Console.WriteLine(data.AsParallel().Where(r => r < 20).Sum()); //===========================================分区器 List il = Enumerable.Range(0, 10000).ToList(); //WithExecutionMode(ParallelExecutionMode.ForceParallelism) //强制并行化整个查询 //WithDegreeOfParallelism() //指定大任务数 var query2 = (from r in Partitioner.Create(il, true).AsParallel().WithExecutionMode(ParallelExecutionMode.ForceParallelism) where r < 20 select r).Sum(); Console.WriteLine("===================================="); Console.WriteLine(query2); Console.WriteLine("===================================="); //===========================================取消长时间运行的任务 var token = new CancellationTokenSource(); new Thread(() => { try { var query3 = (from r in il.AsParallel().WithCancellation(token.Token) where r < 20 select r ).Sum(); Console.WriteLine(query3); } catch (Exception e) { Console.WriteLine(e); } }).Start(); if (Console.ReadLine() == "y" || Console.ReadLine() == "Y") { token.Cancel(); } Console.ReadKey(); } public static void Foreach (IEnumerable s) { Console.WriteLine("=================================="); foreach (var item in s) { Console.WriteLine(item); } } } }
创新互联www.cdcxhl.cn,专业提供香港、美国云服务器,动态BGP最优骨干路由自动选择,持续稳定高效的网络助力业务部署。公司持有工信部办法的idc、isp许可证, 机房独有T级流量清洗系统配攻击溯源,准确进行流量调度,确保服务器高可用性。佳节活动现已开启,新人活动云服务器买多久送多久。
创新互联成立于2013年,我们提供高端网站建设公司、成都网站制作、网站设计、网站定制、成都全网营销推广、小程序制作、微信公众号开发、成都网站营销服务,提供专业营销思路、内容策划、视觉设计、程序开发来完成项目落地,为成都木制凉亭企业提供源源不断的流量和订单咨询。当前文章:并行Linq-创新互联
链接URL:http://myzitong.com/article/eiggd.html