[英]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. 我正在为Windows Phone开发一个应用程序,没有人帮我...我有一个按钮,当单击该按钮时,它会显示页面的正文内容。
After searching a lot about how to download something and not freeze de UI, I found this code that works fine for me: 在搜索了很多有关如何下载内容而不冻结UI的内容之后,我发现这段代码很适合我:
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. (仅需简单一些的代码,对我来说是一件好事)对于逻辑部分,如果您使用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: 您甚至可以完全删除“ AccessTheWeb”功能,因为它适合于一行:
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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.