var list = new List<string> { "https://www.baidu.com","https://associates.amazon.cn/","https://www.amazon.cn","https://www.aliyun.com","http://www.answers.com/" }; Stopwatch sw1 = new Stopwatch(); sw1.Start(); Parallel.For(0, list.Count, i => { WebClient myWebClient = new WebClient(); Stopwatch sw = new Stopwatch(); sw.Start(); myWebClient.OpenRead(list[i]); sw.Stop(); Console.WriteLine("獲取" + list[i] + " 耗時" + sw.ElapsedMilliseconds); }); sw1.Stop(); Console.WriteLine("執行完成 共耗時"+sw1.ElapsedMilliseconds); //Console.ReadKey(); //也能夠用foreach Parallel.ForEach(list, i => { Console.WriteLine(i); });
運行結果:spa
獲取https://www.baidu.com 耗時171 獲取https://www.aliyun.com 耗時214 獲取https://www.amazon.cn 耗時334 獲取https://associates.amazon.cn/ 耗時378 獲取http://www.answers.com/ 耗時1249 執行完成 共耗時1259 https://www.baidu.com http://www.answers.com/ https://associates.amazon.cn/ https://www.aliyun.com https://www.amazon.cn 請按任意鍵繼續. . .