异步方法 async/await

Posted ifordream

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了异步方法 async/await相关的知识,希望对你有一定的参考价值。

不用异步的示例:

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的主要内容,如果未能解决你的问题,请参考以下文章

第126篇: 异步函数(async和await)

js异步回调Async/Await与Promise区别 新学习使用Async/Await

Koa异步处理Async Await和Promise 的使用

用 async/await 来处理异步

js异步回调Async/Await与Promise区别

5 种常见的 async/await 误用 #yyds干货盘点#