从未调用Webclient的DownloadStringCompleted事件处理程序

我正在尝试使用Webclient创建异步HTTP GET请求,但是,注册的回调永远不会被调用。 我也尝试过同步,它运行良好。 我究竟做错了什么?

WebClient asyncWebRequest; public AsyncWebRequest(Uri url) { asyncWebRequest = new WebClient(); url = new Uri("http://www.google.com/"); // string test = asyncWebRequest.DownloadString(url); // this works asyncWebRequest.DownloadStringCompleted += new DownloadStringCompletedEventHandler(asyncWebRequest_DownloadStringCompleted); asyncWebRequest.DownloadStringAsync(url); } void asyncWebRequest_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e) { throw new NotImplementedException(); } 

可能是因为您在完成下载之前处置了WebClient 。 代码执行不会停止在asyncWebRequest.DownloadStringAsync(url); 并且您通过关闭using语句来处置WebClient对象。

尝试在asyncWebRequest_DownloadStringCompleted上部署WebClient

结果

在此处输入图像描述

最简单的解决方案是在AsyncWebRequest(url)方法结束时添加Console.ReadKey() 。 这样asyncWebRequest.DownloadStringAsync(url)就能检索数据。