using System;
using System.Net;
using System.Diagnostics;
using System.Threading.Tasks;
namespace Chapter20AsyncSample_UsingAsyncP394
{
class MyDownloadingString
{
Stopwatch sw = new Stopwatch();//类System.Diagnostic.Stopwatch: Provides a set of methods and properties
//that you can use to accurately measure elapsed time.
public void DoRun()
{
const int LargeNumber = 6000000;
sw.Start();
//下面是保存结果的对象
Task<int> t1 = CountCharactersAsync(1, "http://www.baidu.com");
Task<int> t2 = CountCharactersAsync(2, "http://www.csdn.net");
CountToALargeNumber(1, LargeNumber); CountToALargeNumber(2, LargeNumber);
CountToALargeNumber(3, LargeNumber); CountToALargeNumber(4, LargeNumber);
Console.WriteLine("Chars in http://www.baidu.com :{0}", t1.Result);//获取结果
Console.WriteLine("Chars in http://www.csdn.net :{0}", t2.Result);//获取结果
}
private async Task <int> CountCharactersAsync(int id, string uriString)
{
WebClient wc1 = new WebClient();//类System.Net.WebClient 提供通用的方法用于从资源处(用URI标识)发送和接收数据。
Console.WriteLine("Starting call {0}:{1,4:N0} ms", id, sw.Elapsed.TotalMilliseconds);
//下面的await是上下文关键字
string result = await wc1.DownloadStringTaskAsync(new Uri(uriString));//将资源以字符串形式下载下来。返回一个字符串。
//上面是使用task对象,指定为异步操作
Console.WriteLine(" Call {0} completed:{1,4:N0} ms", id, sw.Elapsed.TotalMilliseconds);
//Console.WriteLine("{0}", result);
return result.Length;
}
private void CountToALargeNumber(int id, int value)
{
for (long i = 0; i < value; i++)
;
Console.WriteLine(" End counting {0}:{1,4:N0} ms", id, sw.Elapsed.TotalMilliseconds);
}
}
class Program
{
static void Main(string[] args)
{
MyDownloadingString ds = new MyDownloadingString();
ds.DoRun();
Console.WriteLine("Hello World!");
}
}
}