我正在尝试使用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();
}
答案 0 :(得分:2)
可能是因为您在完成下载之前处置了WebClient
。代码执行不会在asyncWebRequest.DownloadStringAsync(url);
上停止,并且您通过关闭using语句来处置WebClient
对象。
尝试将WebClient
置于asyncWebRequest_DownloadStringCompleted
。
<强>结果
答案 1 :(得分:0)
最简单的解决方案是在Console.ReadKey()
方法的末尾添加AsyncWebRequest(url)
。这种方式asyncWebRequest.DownloadStringAsync(url)
将能够检索数据。