[英]WebClient doesn't seem to work?
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.在调试时,我可以看到编译器没有进入
client_OpenReadCompleted
事件。 Where's the mistake?哪里错了? I already tried using
DownloadStringCompleted
and DownloadStringAsync
instead, but this doesn't work either.我已经尝试过使用
DownloadStringCompleted
和DownloadStringAsync
,但这也不起作用。
Thanks for your help.谢谢你的帮助。
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.编辑:我已经在 LINQPad 中测试了这个片段,它对我有用。
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?您确定您的代码中没有异常吗?
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"));
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.我建议您不要使用 WebClient,因为这会对您的 UI 产生负面影响,因为由于错误,回调将始终返回 UI 线程。
Here is explained why and how you can use HttpWebRequest as an alternative这里解释了为什么以及如何使用 HttpWebRequest 作为替代
http://social.msdn.microsoft.com/Forums/en-US/windowsphone7series/thread/594e1422-3b69-4cd2-a09b-fb500d5eb1d8 http://social.msdn.microsoft.com/Forums/en-US/windowsphone7series/thread/594e1422-3b69-4cd2-a09b-fb500d5eb1d8
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.