Eggakin Baconwalker
Eggakin Baconwalker

Reputation: 573

Async Task in Windows Phone

I'm developing an App for Windows Phone, and I have no one to help me... I have a button that, when clicked, show the body content of a page.

After searching a lot about how to download something and not freeze de UI, I found this code that works fine for me:

private async void btnBotao_Click(object sender, RoutedEventArgs e)
        {
            string returnedTaskTResult = await AccessTheWebAsync();

            HtmlDocument doc = new HtmlDocument();
            doc.LoadHtml(returnedTaskTResult);
            var body = doc.DocumentNode.SelectSingleNode("//body").WriteContentTo();
            txb.Text = body;
        }

        public async Task<string> AccessTheWebAsync()
        {
            HttpClient client = new HttpClient();
            Task<string> getStringTask = client.GetStringAsync("PAGE");

            string urlContents = await getStringTask;

            return urlContents;
        }

I just want to know if it's correct doing this way... because I know almost nothing about threads, and even if this works for me, maybe it's not the better way to do this... maybe It's incomplete...

Very thanks!!

Upvotes: 1

Views: 675

Answers (2)

McGarnagle
McGarnagle

Reputation: 102723

Looks good -- the only thing I would change is simplify the syntax:

public async Task<string> AccessTheWebAsync()
{
    HttpClient client = new HttpClient();
    return await client.GetStringAsync("PAGE");
}

You could even remove the "AccessTheWeb" function altogether, as it fits in a single line:

private async void btnBotao_Click(object sender, RoutedEventArgs e)
{
    string returnedTaskTResult = await new HttpClient().GetStringAsync("PAGE");

    HtmlDocument doc = new HtmlDocument();
    doc.LoadHtml(returnedTaskTResult);
    var body = doc.DocumentNode.SelectSingleNode("//body").WriteContentTo();
    txb.Text = body;
}

Upvotes: 1

NPadrutt
NPadrutt

Reputation: 13

If I'm not completly wrong you could write this:

        Task<string> getStringTask = client.GetStringAsync("PAGE");

        string urlContents = await getStringTask;

        return urlContents;

also like this:

return await client.GetStringAsync("PAGE");

(Just a bit more straight forward and less code, what for me is a good thing) When it comes to logical part, the framework will handle most of the stuff if you use await / async. So I don't see anything who causes problems

Upvotes: 1

Related Questions