Parallel 类并行任务(仅仅当执行耗时操作时,才有必要使用)
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { Stopwatch sw = new Stopwatch(); sw.Start(); ////非并行任务,总耗时间:3000 //Thread.Sleep(1000); //Thread.Sleep(2000); ////并行任务,总耗时间:2000 //Parallel.Invoke(() => //{ // Thread.Sleep(1000); //}, () => //{ // Thread.Sleep(2000); //}); List<int> list = new List<int>(); var len = 0; object _olock = new object(); var count = 0; //用户计算大于5000数的个数 for (int i = 0; i < 10000; i++) { list.Add(i); } len = list.Count; Parallel.For(1, len, (i) => { lock (_olock) { //耗时操作 Thread.Sleep(1); if (i > 5000) { count++; } } }); sw.Stop(); Console.WriteLine(sw.ElapsedMilliseconds); Console.Read(); } } }
天生我材必有用,千金散尽还复来