DownloadStringTaskAsync on WP7 hangs when retrievi

2019-09-02 11:35发布

问题:

I converted a bunch of WP7 code to use DownloadStringTaskAsync instead of DownloadStringAsync using the Async CTP SP1. It wasn't working so I boiled down my code a bunch and ended up with these 2 lines:

var wc = new WebClient();
var result = wc.DownloadStringTaskAsync("http://www.weather.gov").Result;

If I run this method with a console app on my windows machine. Its works as I expect and I get a string with the contents of weather.gov. If I run the same 2 lines in the constructor of App in a blank WP7 app, it hangs while waiting for Result to become available.

Can anyone help me fix these lines so they will work on the phone? Or is this a bug in the CTP and I should skip it for now.

回答1:

Windows Phone brings back HTTP requests on the UI thread. By accessing Result, you are blocking the UI thread, thus making it impossible for the response to come back.

Considering you are using the async CTP, why would you want to block at all?

var result = await wc.DownloadStringTaskAsync("http://www.weather.gov");