async / await上的MSDN示例 – 在await调用之后我不能到达断点吗?

在async / await上尝试MSDN的例子时,为什么我在await运算符之后无法达到断点?

private static void Main(string[] args) { AccessTheWebAsync(); } private async Task AccessTheWebAsync() { // You need to add a reference to System.Net.Http to declare client. HttpClient client = new HttpClient(); // GetStringAsync returns a Task. That means that when you await the // task you'll get a string (urlContents). Task getStringTask = client.GetStringAsync("http://msdn.microsoft.com"); // You can do work here that doesn't rely on the string from GetStringAsync. /*** not relevant here ***/ //DoIndependentWork(); // The await operator suspends AccessTheWebAsync. // - AccessTheWebAsync can't continue until getStringTask is complete. // - Meanwhile, control returns to the caller of AccessTheWebAsync. // - Control resumes here when getStringTask is complete. // - The await operator then retrieves the string result from getStringTask. string urlContents = await getStringTask; // The return statement specifies an integer result. // Any methods that are awaiting AccessTheWebAsync retrieve the length value. return urlContents.Length; } 

我的理解是await是一个构造,它从开发人员那里抽象出异步流 – 让他/她好像在同步工作。 换句话说,在上面的代码中,我不关心getStringTask如何以及何时完成,我只关心它完成并使用它的结果。 我希望在某个时候等待电话之后能够达到断点。

在此处输入图像描述

您可以从Console应用程序的Main方法调用异步方法,而无需等待异步方法完成。 因此,您的流程会在您的任务有机会完成之前终止。

由于您无法将Console应用程序的Main转换为异步( async Task )方法,因此您必须通过调用Wait.Result来阻止异步方法:

 private static void Main(string[] args) { AccessTheWebAsync().Wait(); } 

要么

 private static void Main(string[] args) { var webTask=AccessTheWebAsync(); //... do other work until the resuls is actually needed var pageSize=webTask.Result; //... now use the returned page size }