问题
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