Pergunta

Greetings,

I'm trying to download a web page with the following code:

public partial class MainPage : PhoneApplicationPage
{
    private static string result = null;

    // Constructor
    public MainPage()
    {
        InitializeComponent();

        LoadFeeds();
    }

    public static void LoadFeedsCompleted(Object sender, DownloadStringCompletedEventArgs e)
    {
        result = e.Result;
    }

    private void LoadFeeds()
    {
        string url = "http://www.cornfedsystems.com";
        Uri uri = new Uri(url);
        WebClient client = new WebClient();
        client.DownloadStringCompleted += LoadFeedsCompleted;
        client.AllowReadStreamBuffering = true;
        client.DownloadStringAsync(uri);
        for (; ; )
        {
            if (result != null)
            {
                console.Text = result;
                result = null;
            }
            Thread.Sleep(100);
        }
    }

}

This code compiles fine but when I start it in the emulator, it just hangs with the clock screen, i.e. wait. I put in some breakpoints and I can see that the for loop is spinning but the value of result is never being updated. console is a TextBox. Any thoughts on what might be happening?

Thanks,

FM

Foi útil?

Solução

I fail to see the purpose of the loop that you have in your code, as well as that of the result string. Here is what I have for your issue.

Here is the code that will ultimately trigger the process:

string url = "http://www.cornfedsystems.com";
Uri uri = new Uri(url);
WebClient client = new WebClient();
client.DownloadStringCompleted += new DownloadStringCompletedEventHandler(client_DownloadStringCompleted);
client.AllowReadStreamBuffering = true;
client.DownloadStringAsync(uri);

Here is the event handler:

void client_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
    Debug.WriteLine(e.Result);
}

All result processing should be done in the event handler that will be triggered when everything is ready (in your case - the string is downloaded). With DowhloadStringAsync you will get the page source - it is constant and doesn't change (unlike a dynamic feed), so you don't need the loop there.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top