在异步编程前,先举个没有异步的示例:

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 using System.Threading.Tasks;
 6 using System.Diagnostics;//
 7 using System.Net;//
 8 
 9 namespace ConsoleApplication6
10 {
11     class MyDownloadString
12     {
13         Stopwatch sw = new Stopwatch();//
14 
15         public void DoRun()
16         {
17             const int LargeNumber = 6000000;
18             sw.Start();
19 
20             int t1 = CountCharacters(1, "http://www.cnblogs.com");
21             int t2 = CountCharacters(2, "http://www.163.com");
22 
23             CountToALargeNumber(1, LargeNumber);
24             CountToALargeNumber(2, LargeNumber);
25             CountToALargeNumber(3, LargeNumber);
26             CountToALargeNumber(4, LargeNumber);
27 
28             Console.WriteLine("Chars in http://www.microsoft.com          :{0}", t1);
29             Console.WriteLine("Chars in http://www.illustratedcsharp.com  :{0}", t2);
30         }
31 
32         private int CountCharacters(int id, string uriString)
33         {
34             WebClient wc1 = new WebClient();
35 
36             Console.WriteLine("Starting call {0}    :    {1, 4:N0} ms", id, sw.Elapsed.TotalMilliseconds);//开始下载网页时间
37             string result = wc1.DownloadString(new Uri(uriString));//正式下载网页数据
38             Console.WriteLine("Call {0} completed   :    {1, 4:N0} ms", id, sw.Elapsed.TotalMilliseconds);//完成网页下载
39             //Console.WriteLine(result);
40             return result.Length;
41         }
42 
43         private void CountToALargeNumber(int id, int value)
44         {
45             for (long i = 0; i < value; i++) ;
46 
47             Console.WriteLine("End counting {0}     :   {1, 4:N0} ms", id, sw.Elapsed.TotalMilliseconds);//一个循环结束时间,目的是延时
48 
49         }
50     }
51     class Program
52     {
53         static void Main(string[] args)
54         {
55             MyDownloadString ds = new MyDownloadString();
56             ds.DoRun();
57             Console.ReadKey();
58         }
59 
60     }
61 }
62 //output:
63 //------------------------------------------------------------------------
64 //Starting call 1    :       1 ms
65 //Call 1 completed:        207 ms
66 //Starting call 2    :     207 ms
67 //Call 2 completed:        382 ms
68 //End counting 1  :    424 ms
69 //End counting 2  :    447 ms
70 //End counting 3  :    469 ms
71 //End counting 4  :    491 ms
72 //Chars in http://www.microsoft.com          :41177
73 //Chars in http://www.illustratedcsharp.com  :6870
View Code

相关文章: