測試 Parallel.ForEach和普通的foreach的耗時
阿新 • • 發佈:2020-10-28
static void Main(string[] args) { //定義一個list List<string> list = new List<string> { "1", "2", "3", "4" }; System.Diagnostics.Stopwatch wacth = new System.Diagnostics.Stopwatch(); wacth.Start(); //多執行緒的foreach,會開多個執行緒同時執行Handle方法Parallel.ForEach(list, p => Handle(p)); wacth.Stop(); Console.WriteLine(wacth.ElapsedMilliseconds); System.Diagnostics.Stopwatch wacth1 = new System.Diagnostics.Stopwatch(); wacth1.Start(); //一個執行緒執行Handle方法 foreach(var p in list) { Handle(p); } wacth1.Stop(); Console.WriteLine(wacth1.ElapsedMilliseconds); } static void Handle(string str) { Console.WriteLine(str); Thread.Sleep(1000); }
得到的結果
發現多執行緒執行完之後輸出的順序不再是1,2,3,4