C#5.0 异步编程async/await用法

微软在发布VS2012的同时推出了C#5.0,其中包含了async和await



代码如下:

 class Program
    {
        private static readonly Stopwatch watch = new Stopwatch();
        static void Main(string[] args)
        {
            watch.Start();
            const string url1 = "https://www.zhihu.com/";
            const string url2 = "https://www.zhihu.com/question/269110219/answer/396519652";

            Task<int> t1 = downloadurl(1, url1);
            Task<int> t2 = downloadurl(2, url2);

            for (int x = 0; x < 3; x++)
            {
                addstring(x);
            }
            Console.WriteLine($"{"url1"} 的字符个数:{t1.Result}");
            Console.WriteLine($"{"url2"} 的字符个数:{t2.Result}");

            Console.Read();
        }
        public static void addstring(int id)
        {
            var s = "";
            for (int x = 0; x < 20000; x++)
            {
                s += x;
            }
            Console.WriteLine($"id = {id} 的 addstring 方法完成:{watch.ElapsedMilliseconds} ms");
        }
        public static async Task<int> downloadurl(int id, string adress)
        {
            var webclient = new WebClient();
            Console.WriteLine($"开始调用 id = {id}:{watch.ElapsedMilliseconds} ms");
            var result = await webclient.DownloadStringTaskAsync(adress);
            Console.WriteLine($"调用完成 id = {id}:{watch.ElapsedMilliseconds} ms");
            return result.Length;
        }
    }




未完待续。。。。。




原文地址:https://www.cnblogs.com/kevinWu7/p/10163488.html