uot;);
Console.WriteLine(DateTime.Now.ToString("mm:ss"));
Console.ReadLine();
进度更新事件处理方法:
static void wc_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{
Console.WriteLine("{0} downloaded {1} of {2} bytes. {3} % complete...", (string)e.UserState, e.BytesReceived, e.TotalBytesToReceive, e.ProgressPercentage);
}
完成下载事件处理方法:
static void wc_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
Console.WriteLine(DateTime.Now.ToString("mm:ss"));
Console.WriteLine(e.Result.Substring(0, 300));
}
程序输出结果:
我们可以看到WebClient的DownloadStringAsync方法在内部使用了WebRequest:
public void DownloadStringAsync(Uri address, object userToken)
{
if (Logging.On)
{
Logging.Enter(Logging.Web, this, "DownloadStringAsync", address);
}
if (address == null)
{
throw new ArgumentNullException("address");
}
this.InitWebClientAsync();
this.ClearWebClientState();
AsyncOperation asyncOp = AsyncOperationManager.CreateOperation(userToken);
this.m_AsyncOp = asyncOp;
try
{
WebRequest request = this.m_WebRequest = this.GetWebRequest(this.GetUri (address));
this.DownloadBits(request, null, new CompletionDelegate (this.DownloadStringAsyncCallback), asyncOp
);
}
catch (Exception exception)
{
if (((exception is ThreadAbortException) || (exception is StackOverflowException)) || (exception is OutOfMemoryException))
{
throw;
}
if (!(exception is WebException) && !(exception is SecurityException))
{
exception = new WebException(SR.GetString("net_webclient"), exception);
}
this.DownloadStringAsyncCallback(null, exception, asyncOp);
}
catch
{
Exception exception2 = new WebException(SR.GetString("net_webclient"), new Exception(SR.GetString("net_nonClsCompliantException")));
this.DownloadStringAsyncCallback(null, exception2, asyncOp);
}
if (Logging.On)
{
Logging.Exit(Logging.Web, this, "DownloadStringAsync", "");
}
}
而且,使用了WebRequest的基于IAsyncResult的APM,可以看看DownloadBits的定义:
private byte[] DownloadBits(WebRequest request, Stream writeStream, CompletionDelegate completionDelegate, AsyncOperation asyncOp)
{
WebResponse response = null;
DownloadBitsState state = new DownloadBitsState(request, writeStream, completionDelegate, asyncOp, this.m_Progress, this);
if (state.Async)
{
request.BeginGetResponse(new AsyncCallback(WebClient.DownloadBitsResponseCallback), state);
return null;
}
response = this.m_WebResponse = this.GetWebResponse(request);
int bytesRe
|