【发布时间】:2014-07-22 18:15:16
【问题描述】:
我编写了一个测试应用程序来帮助我理解等待/异步。我有一个方法MethodAsync1() 可以正常工作。但是,当我从 Main() 调用它时,我无法弄清楚如何等待 MethodAsync1() 完成。请参阅下面的代码。
class Program
{
static void Main(string[] args)
{
Debug.WriteLine(DateTime.Now + " Main()1");
Task<String> v1 = MethodAsync1();
Debug.WriteLine(DateTime.Now + " Main()2 - prints out before Method1 finishes");
// I now want to wait for MethosAsync1() to complete before I go further.
// This line has error:
// Error 1 The 'await' operator can only be used within an async
// method. Consider marking this method with the 'async' modifier and
// changing its return type to 'Task'.
String v2 = await v1;
Debug.WriteLine(DateTime.Now + " Main()3 - Method1() now finished");
}
static async Task<String> MethodAsync1()
{
Debug.WriteLine(DateTime.Now + " Method1()1 ");
HttpClient client = new HttpClient();
Task<HttpResponseMessage> responseTask = client.GetAsync("http://bbc.co.uk");
// Do other stuff
Debug.WriteLine(DateTime.Now + " Method1()2 ");
// Wait for it to finish - yield thread back to Main()
var response= await responseTask;
// responseTask has completed - so thread goes back here and method returns fully
Debug.WriteLine(DateTime.Now + " Method1()3 ");
return "finished";
}
}
【问题讨论】:
-
你能让
main也成为async方法吗? -
不,它不会让我说:
'await1.Program.Main(string[])': an entry point cannot be marked with the 'async' modifier -
为什么
main应该是异步的?这是没有意义的。阻塞它的线程直到你得到结果。 -
@spiderplant0 你不能在 main 中等待。使用
v1.Result -
找到了我自己的问题的答案:stackoverflow.com/a/17579418/120955