Reputation: 11395
I've got the following code:
WebClient client = new WebClient();
client.OpenReadAsync(new Uri("whatever"));
client.OpenReadCompleted += new OpenReadCompletedEventHandler(client_OpenReadCompleted);
and:
void client_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
{
Stream reply = (Stream)e.Result;
StreamReader s;
s = new StreamReader(reply);
this._code = s.ReadToEnd();
s.Close();
}
While debugging I can see the compiler doesn't move into the client_OpenReadCompleted
event. Where's the mistake? I already tried using DownloadStringCompleted
and DownloadStringAsync
instead, but this doesn't work either.
Thanks for your help.
Upvotes: 3
Views: 3299
Reputation: 2918
I would advice you to not use the WebClient since this has a negative impact on your UI because the callback will always return on the UI thread because of a bug.
Here is explained why and how you can use HttpWebRequest as an alternative
Upvotes: 0
Reputation: 13019
Try to put the event handler before you call the async method.
WebClient client = new WebClient();
client.OpenReadCompleted += new OpenReadCompletedEventHandler(client_OpenReadCompleted);
client.OpenReadAsync(new Uri("www.google.it"));
EDIT: I have tested this snippet inside LINQPad and it works for me.
void Main()
{
var client = new System.Net.WebClient();
client.OpenReadCompleted += (sender, e) =>
{
"Read successfully".Dump();
};
client.OpenReadAsync(new Uri("http://www.google.it"));
Console.ReadLine();
}
Are you sure there is no exception inside your code?
Upvotes: 1
Reputation: 4634
Your order of operations is incorrect.
//create an instance of webclient
WebClient client = new WebClient();
//assign the event handler
client.OpenReadCompleted += new OpenReadCompletedEventHandler(client_OpenReadCompleted);
//call the read method
client.OpenReadAsync(new Uri("whatever"));
Upvotes: 1