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