1. 程式人生 > >非同步方法 async/await

非同步方法 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);
        }