WebClient doesn't seem to work?
I've got the following code:
WebClient client = new WebClient开发者_JAVA百科();
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.
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"));
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?
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
http://social.msdn.microsoft.com/Forums/en-US/windowsphone7series/thread/594e1422-3b69-4cd2-a09b-fb500d5eb1d8
精彩评论