C# Windows Phone 7.1 HTTP GET with DownloadStringAsync
在网上搜索了大约4个小时后,我仍然不理解WindowsPhone7上的异步功能。我试图运行该代码,但似乎从未引发webClient的事件“DownloadStringCompleted”。我试图在这里等待答案,但它只是冻结了我的应用程序。任何人都可以帮助解释为什么它不起作用C# Windows Phone 7.1 HTTP GET with DownloadStringAsync,c#,windows-phone-7,asynchronous,download,C#,Windows Phone 7,Asynchronous,Download,在网上搜索了大约4个小时后,我仍然不理解WindowsPhone7上的异步功能。我试图运行该代码,但似乎从未引发webClient的事件“DownloadStringCompleted”。我试图在这里等待答案,但它只是冻结了我的应用程序。任何人都可以帮助解释为什么它不起作用 internal string HTTPGet() { string data = null; bool exit = false; WebClient web
internal string HTTPGet()
{
string data = null;
bool exit = false;
WebClient webClient = new WebClient();
webClient.UseDefaultCredentials = true;
webClient.DownloadStringCompleted += (sender, e) =>
{
if (e.Error == null)
{
data = e.Result;
exit = true;
}
};
webClient.DownloadStringAsync(new Uri(site, UriKind.Absolute));
//while (!exit)
// Thread.Sleep(1000);
return data;
}
嗯。找到东西了!
耶!:) 这不是emulator的问题。您希望从HttpGet()方法返回数据,但在webClient发出实际响应之前,数据已经返回(为null)。因此,我建议您对代码进行一些更改,然后再试一次
WebClient client = new WebClient();
client.DownloadStringCompleted += new DownloadStringCompletedEventHandler(client_DownloadStringCompleted);
client.DownloadStringAsync(new Uri(site, UriKind.Absolute));
然后在DownloadCompleted事件处理程序(或回调)中,手动填充实际结果
void client_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
var response= e.Result; // Response obtained from the site
}
这不是emulator的问题。您希望从HttpGet()方法返回数据,但在webClient发出实际响应之前,数据已经返回(为null)。因此,我建议您对代码进行一些更改,然后再试一次
WebClient client = new WebClient();
client.DownloadStringCompleted += new DownloadStringCompletedEventHandler(client_DownloadStringCompleted);
client.DownloadStringAsync(new Uri(site, UriKind.Absolute));
然后在DownloadCompleted事件处理程序(或回调)中,手动填充实际结果
void client_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
var response= e.Result; // Response obtained from the site
}
因此,没有任何方法可以在相同的方法中获得响应?这就是Async的特点,您无法确定它何时完成下载。因此,当它完成时,它只是在事件处理程序中返回。因此,没有任何方法可以在同一个方法中获得该响应?这就是异步的问题,您无法确定它何时完成下载。因此,当它完成时,它只是在事件处理程序中返回。