【发布时间】:2019-11-14 11:12:22
【问题描述】:
如果 await 只能由 async 方法使用,我如何从 MainPage() 调用任务?
我的代码示例:
public MainPage()
{
InitializeComponent();
label.Text=await Task.Run(TaskTest); //this doesn't work
}
private async Task<string> TaskTest()
{
try
{
using (WebClient client = new WebClient())
{
return await client.DownloadStringTaskAsync("https://www.example.com/return.php");
//also tried w/ no success:
//return client.DownloadStringTaskAsync("https://www.example.com/return.php").Result;
}
}
catch (Exception)
{
throw;
}
}
【问题讨论】:
-
你没有。构造函数并不意味着创建异步流。你可能想看看this question
-
label.Text = await Task.Run 非常混乱。 UI 在单独的线程上运行。您可能希望为 await 任务分配一个值,然后将其分配给 label.Text。