Webclient's DownloadStringCompleted event handler never called

时间秒杀一切 提交于 2020-01-11 10:59:37

问题


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();
}

回答1:


Maybe because you disposing the WebClient before it finished downloading. The code execution don't stop on asyncWebRequest.DownloadStringAsync(url); and you are disposing the WebClient object by closing the using statement.

try to dispose the WebClient on asyncWebRequest_DownloadStringCompleted.

results




回答2:


The simpliest solution is to add Console.ReadKey() at the end of AsyncWebRequest(url) method. This way asyncWebRequest.DownloadStringAsync(url) will be able to retrieve data.



来源:https://stackoverflow.com/questions/7373172/webclients-downloadstringcompleted-event-handler-never-called

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!