Web 客户端的 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();
}
I'm trying to make an asynchronous HTTP GET request using Webclient, however, the registered callback never gets called. I've also tried with the sync one, and it worked fine. What am I doing wrong?
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();
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
也许是因为您在下载完成之前就处理了
WebClient
。代码执行不会在asyncWebRequest.DownloadStringAsync(url);
上停止,并且您将通过关闭 using 语句来处置WebClient
对象。尝试在
asyncWebRequest_DownloadStringCompleted
上处置WebClient
。结果
Maybe because you disposing the
WebClient
before it finished downloading. The code execution don't stop onasyncWebRequest.DownloadStringAsync(url);
and you are disposing theWebClient
object by closing the using statement.try to dispose the
WebClient
onasyncWebRequest_DownloadStringCompleted
.results
最简单的解决方案是在
AsyncWebRequest(url)
方法末尾添加Console.ReadKey()
。这样asyncWebRequest.DownloadStringAsync(url)
将能够检索数据。The simpliest solution is to add
Console.ReadKey()
at the end ofAsyncWebRequest(url)
method. This wayasyncWebRequest.DownloadStringAsync(url)
will be able to retrieve data.