所謂的數據並行的條件是:編程
一、擁有大量的數據。async
二、對數據的邏輯操做都是一致的。this
三、數據之間沒有順序依賴。spa
運行並行編程能夠充分的利用如今多核計算機的優點。記錄代碼以下:pwa
public class ParallerFor { public List<string> studentList; public ParallerFor() { this.studentList = new List<string>(); for (int i = 0; i < 50; i++) { this.studentList.Add("xiaochun"+i.ToString()); } } public void ParallerTest() { var sw = Stopwatch.StartNew(); foreach (string str in this.studentList) { Console.WriteLine("this is sync "+str); Thread.Sleep(800); } Console.WriteLine("運行時間:"+sw.Elapsed.ToString()); } public void ParallerAsyncTest() { var sw = Stopwatch.StartNew(); Action<int> ac = (i) => { Console.WriteLine("this is async " + this.studentList[i]); Thread.Sleep(800); }; Parallel.For(0, this.studentList.Count,ac);//這裏的0是指循環的起點 Console.WriteLine("運行時間:" + sw.Elapsed.ToString()); } public void ParallalForEachTest() { var sw = Stopwatch.StartNew(); Action<string> ac = (str) => { int num = int.Parse(str.Replace("xiaochun",string.Empty)); if (num > 10) { Console.WriteLine(str); Thread.Sleep(1000); } }; //限定最大並行數目 ParallelOptions op = new ParallelOptions(); op.MaxDegreeOfParallelism = 4; Parallel.ForEach(this.studentList,op,ac); //這裏沒有限定最大並行數目 //Parallel.ForEach(this.studentList,ac); } }