PLINQ2
using System; using System.Text; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using System.Diagnostics; using System.Linq; namespace Test { class Program { public static string DateTime_Now_ToString() { return DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"); } /// <summary> /// PINQ2 /// </summary> static void Main() { Console.WriteLine("主线程Id:" + Thread.CurrentThread.ManagedThreadId.ToString()); Console.WriteLine(); var intArray = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; Stopwatch sw = new Stopwatch(); sw.Start(); var result = intArray.Where(i => Work(i)); foreach (int item in result) { Console.WriteLine("LINQ遍历值:" + item.ToString()); } sw.Stop(); Console.WriteLine("LINQ耗时:{0},计数:{1}", sw.ElapsedMilliseconds.ToString(), sw.ElapsedTicks.ToString()); Console.WriteLine(); sw.Restart(); var result2 = intArray.AsParallel().Where(i => Work(i)); foreach (int item in result2) { Console.WriteLine("PLINQ遍历值:" + item.ToString()); } sw.Stop(); Console.WriteLine("PLINQ耗时:{0},计数:{1}", sw.ElapsedMilliseconds.ToString(), sw.ElapsedTicks.ToString()); Console.WriteLine("\n执行完成" + DateTime_Now_ToString()); Console.ReadLine(); } private static bool Work(int index) { int taskId = 0; taskId = Task.CurrentId ?? 0; int threadId = Thread.CurrentThread.ManagedThreadId; string date = DateTime.Now.ToString(); Console.WriteLine("当前值:{0},任务Id:{1},线程Id:{2},当前时间:{3}", index.ToString(), taskId, threadId, date); Thread.Sleep(TimeSpan.FromMilliseconds(5000)); //Thread.SpinWait(5000); return index > 5; } } }
打印运行结果:
/* 主线程Id:9 当前值:1,任务Id:0,线程Id:9,当前时间:2016/8/30 23:04:01 当前值:2,任务Id:0,线程Id:9,当前时间:2016/8/30 23:04:06 当前值:3,任务Id:0,线程Id:9,当前时间:2016/8/30 23:04:11 当前值:4,任务Id:0,线程Id:9,当前时间:2016/8/30 23:04:16 当前值:5,任务Id:0,线程Id:9,当前时间:2016/8/30 23:04:21 当前值:6,任务Id:0,线程Id:9,当前时间:2016/8/30 23:04:26 LINQ遍历值:6 当前值:7,任务Id:0,线程Id:9,当前时间:2016/8/30 23:04:31 LINQ遍历值:7 当前值:8,任务Id:0,线程Id:9,当前时间:2016/8/30 23:04:36 LINQ遍历值:8 当前值:9,任务Id:0,线程Id:9,当前时间:2016/8/30 23:04:41 LINQ遍历值:9 当前值:10,任务Id:0,线程Id:9,当前时间:2016/8/30 23:04:46 LINQ遍历值:10 LINQ耗时:50077,计数:117105297 当前值:1,任务Id:1,线程Id:10,当前时间:2016/8/30 23:04:51 当前值:4,任务Id:2,线程Id:13,当前时间:2016/8/30 23:04:51 当前值:7,任务Id:3,线程Id:12,当前时间:2016/8/30 23:04:51 当前值:9,任务Id:4,线程Id:11,当前时间:2016/8/30 23:04:51 当前值:2,任务Id:1,线程Id:10,当前时间:2016/8/30 23:04:56 当前值:5,任务Id:2,线程Id:13,当前时间:2016/8/30 23:04:56 当前值:8,任务Id:3,线程Id:12,当前时间:2016/8/30 23:04:56 当前值:10,任务Id:4,线程Id:11,当前时间:2016/8/30 23:04:56 当前值:3,任务Id:1,线程Id:10,当前时间:2016/8/30 23:05:01 当前值:6,任务Id:2,线程Id:13,当前时间:2016/8/30 23:05:01 PLINQ遍历值:7 PLINQ遍历值:9 PLINQ遍历值:8 PLINQ遍历值:10 PLINQ遍历值:6 PLINQ耗时:15117,计数:35351423 执行完成2016-08-30 23:05:06 */

浙公网安备 33010602011771号