码迷,mamicode.com
首页 > 其他好文 > 详细

异步方法 async/await

时间:2018-11-06 11:15:01      阅读:121      评论:0      收藏:0      [点我收藏+]

标签:var   edm   int   span   +=   lis   ext   tchar   wait   

不用异步的示例:

static void Main(string[] args)
        {
            Watch.Start();
            string Url1 = "Http://www.tmall.com";
            string Url2 = "http://www.taobao.com";
            var result1 = CountCharacters(1, Url1);
            var result2 = CountCharacters(2, Url2);
            for (int i = 0; i < 3; i++)
            {
                ExtraOperation(i);
            }
            Console.WriteLine("{0}的字符个数{1}", Url1, result1);
            Console.WriteLine("{0}的字符个数{1}", Url2, result1);
            Console.ReadLine();
        }

        public static int CountCharacters(int id, string Url)
        {
            var wc = new WebClient();
            Console.WriteLine("开始调用:id:{0},{1}", id, Watch.ElapsedMilliseconds);
            var result = wc.DownloadString(Url);
            Console.WriteLine("调用完成:id:{0},{1}", id, Watch.ElapsedMilliseconds);
            return result.Length;
        }

        public static void ExtraOperation(int id)
        {
            var s = "";
            for (int i = 0; i < 6000; i++)
            {
                s += i;
            }
            Console.WriteLine("id={0} 的 ExtraOperation调用完成用时{1}", id, Watch.ElapsedMilliseconds);
        }

 

使用异步的示例 

static void Main(string[] args)
        {
            Watch.Start();
            string Url1 = "Http://www.tmall.com";
            string Url2 = "http://www.taobao.com";
            Task<int> t1 = CountCharacters(1, Url1);
            Task<int> t2 = CountCharacters(2, Url2);
            for (int i = 0; i < 3; i++)
            {
                ExtraOperation(i);
            }
            Console.WriteLine("{0}的字符个数{1}", Url1, t1.Result);
            Console.WriteLine("{0}的字符个数{1}", Url2, t2.Result);
            Console.ReadLine();
        }

        public static async Task<int> CountCharacters(int id, string Url)
        {
            var wc = new WebClient();
            Console.WriteLine("开始调用:id:{0},{1}", id, Watch.ElapsedMilliseconds);
            var result = await wc.DownloadStringTaskAsync(Url);
            Console.WriteLine("调用完成:id:{0},{1}", id, Watch.ElapsedMilliseconds);
            return result.Length;
        }

        public static void ExtraOperation(int id)
        {
            var s = "";
            for (int i = 0; i < 6000; i++)
            {
                s += i;
            }
            Console.WriteLine("id={0} 的 ExtraOperation调用完成用时{1}", id, Watch.ElapsedMilliseconds);
        }

 

异步方法 async/await

标签:var   edm   int   span   +=   lis   ext   tchar   wait   

原文地址:https://www.cnblogs.com/ifordream/p/9913139.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!