c# Parallel 并行运算 异步处理

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);
            });

运行结果:

获取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
请按任意键继续. . .

 

posted @ 2018-02-06 00:37  虚若影  阅读(464)  评论(0编辑  收藏  举报