2

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();
}
Patrick D'Souza
  • 3,491
  • 2
  • 22
  • 39
norbip
  • 625
  • 7
  • 21

2 Answers2

2

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

enter image description here

Samich
  • 29,157
  • 6
  • 68
  • 77
  • I've updated the code in the question. It's still not working. – norbip Sep 10 '11 at 17:02
  • Well, yes, the problem was that I've tested it as a console app, and it exited before this got called. (see the first comment on my question). – norbip Sep 10 '11 at 17:10
  • 1
    Yes, I saw it. Put `Console.ReadLine()` at the end of your `Main` method to wait till the end of async call – Samich Sep 10 '11 at 17:12
0

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.

dstrants
  • 7,423
  • 2
  • 19
  • 27