WebClient似乎不起作用?

时间:2011-06-08 17:25:44

标签: c# windows-phone-7 webclient

我有以下代码:

WebClient client = new WebClient();
client.OpenReadAsync(new Uri("whatever"));
client.OpenReadCompleted += new OpenReadCompletedEventHandler(client_OpenReadCompleted);

void client_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
{
  Stream reply = (Stream)e.Result;
  StreamReader s;
  s = new StreamReader(reply);
  this._code = s.ReadToEnd();
  s.Close();
}

调试时我可以看到编译器没有进入client_OpenReadCompleted事件。哪里出错了?我已尝试使用DownloadStringCompletedDownloadStringAsync,但这也不起作用。

感谢您的帮助。

3 个答案:

答案 0 :(得分:1)

尝试在调用异步方法之前放置事件处理程序。

WebClient client = new WebClient();
client.OpenReadCompleted += new OpenReadCompletedEventHandler(client_OpenReadCompleted);
client.OpenReadAsync(new Uri("www.google.it"));

编辑:我在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();
}

您确定代码中没有异常吗?

答案 1 :(得分:1)

您的操作顺序不正确。

//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"));

答案 2 :(得分:0)

我建议您不要使用WebClient,因为这会对您的UI产生负面影响,因为由于错误,回调将始终在UI线程上返回。

这里解释了为什么以及如何使用HttpWebRequest作为替代

http://social.msdn.microsoft.com/Forums/en-US/windowsphone7series/thread/594e1422-3b69-4cd2-a09b-fb500d5eb1d8

相关问题