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()); //===========================================分區(qū)器 List il = Enumerable.Range(0, 10000).ToList(); //WithExecutionMode(ParallelExecutionMode.ForceParallelism) //強制并行化整個查詢 //WithDegreeOfParallelism() //指定大任務數(shù) 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); } } } }
創(chuàng)新互聯(lián)www.cdcxhl.cn,專業(yè)提供香港、美國云服務器,動態(tài)BGP最優(yōu)骨干路由自動選擇,持續(xù)穩(wěn)定高效的網(wǎng)絡助力業(yè)務部署。公司持有工信部辦法的idc、isp許可證, 機房獨有T級流量清洗系統(tǒng)配攻擊溯源,準確進行流量調(diào)度,確保服務器高可用性。佳節(jié)活動現(xiàn)已開啟,新人活動云服務器買多久送多久。
創(chuàng)新互聯(lián)成立于2013年,我們提供高端網(wǎng)站建設公司、成都網(wǎng)站制作、網(wǎng)站設計、網(wǎng)站定制、成都全網(wǎng)營銷推廣、小程序制作、微信公眾號開發(fā)、成都網(wǎng)站營銷服務,提供專業(yè)營銷思路、內(nèi)容策劃、視覺設計、程序開發(fā)來完成項目落地,為成都木制涼亭企業(yè)提供源源不斷的流量和訂單咨詢。