不用異步的示例:異步
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); }
使用異步的示例 async
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); }