简体   繁体   中英

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!!

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

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM